最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - CSS scale triggered by mouseover or onclick? - Stack Overflow

programmeradmin5浏览0评论

I have some CSS that scales images, which works fine.

The problem is it gets applied to every image on the page. What I want is to apply it ONLY to an image if I mouseover or onclick.

Because images are inserted by a CMS used by non-tech writers, they don't have the skills to get into the image tag itself to insert a class. This is why I want the scaling CSS triggered by mouseover or onclick.

I've struggled to get a piece of javascript to do the job and would appreciate some help

I have some CSS that scales images, which works fine.

The problem is it gets applied to every image on the page. What I want is to apply it ONLY to an image if I mouseover or onclick.

Because images are inserted by a CMS used by non-tech writers, they don't have the skills to get into the image tag itself to insert a class. This is why I want the scaling CSS triggered by mouseover or onclick.

I've struggled to get a piece of javascript to do the job and would appreciate some help

Share Improve this question asked Jul 7, 2014 at 20:47 Stefan YoungsStefan Youngs 531 gold badge1 silver badge7 bronze badges 3
  • Are you trying to extend the cms editor to let non technical editors apply the css scaling to images they insert? – Hurricane Hamilton Commented Jul 7, 2014 at 20:51
  • 1 have you tried the :hover css pseudo-selector? – user428517 Commented Jul 7, 2014 at 20:52
  • fine can you show some code... – user2628521 Commented Jul 7, 2014 at 21:43
Add a ment  | 

2 Answers 2

Reset to default 2

You just bind the event to the tag and use this:

   var images = document.getElementsByTagName("img");
   for (var i=0;i<images.length;i++) {
        images[i].onmouseover = imgScale;
        images[i].onclick = imgScale;
   }
   function imgScale(e) {
       this.style.width = 500px; //whatever
       this.setAttribute("class", "image-scale");
   }

If jQuery:

$('img').on('hover click', function() { 
       $(this).css('width','500px');
       $(this).addClass('image-scale');
});

Even better, if you only need on hover you can use just CSS:

img:hover {
   width: 500px;
}

You could try using

img:active

To detect a click, but I believe it will only make changes while the mouse is pressed down, as soon as they let up it is no longer :active

You may try using CSS 3 for scaling. Have a look at this fiddle.

HTML:

<img src="http://lorempixel./200/200/sports"/>
<img src="http://lorempixel./200/200/nature"/>
<img src="http://lorempixel./200/200/city"/>
<img src="http://lorempixel./200/200/sports"/>
<img src="http://lorempixel./200/200/animals"/>

CSS:

img {
    -webkit-transition: all 300ms 0ms ease-in-out;
    transition: all 300ms 0ms ease-in-out;
    width: 50px;
}

img:hover {
    -webkit-transform: scale(1.4);
    transform: scale(1.4);
}
发布评论

评论列表(0)

  1. 暂无评论