CSS缩放由鼠标悬停或点击触发

CSS scale triggered by mouseover or onclick?

本文关键字:悬停 缩放 鼠标 CSS      更新时间:2023-09-26

我有一些CSS来缩放图像,效果很好。

问题是它被应用到页面上的每个图像。我想要的是应用它只对图像,如果我鼠标悬停或点击。

由于图像是由非技术作者使用的CMS插入的,因此他们不具备进入图像标记本身以插入类的技能。这就是为什么我想要缩放CSS触发鼠标悬停或点击。

我一直在努力得到一块javascript来做这项工作,并将感谢一些帮助

您只需将事件绑定到标签并使用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");
   }
如果jQuery:

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

更好的是,如果你只需要悬停,你可以使用CSS:

img:hover {
   width: 500px;
}

你可以试着用

img:active

检测点击,但我相信它只会做出改变,而鼠标按下,一旦他们放松它不再是:active

你可以尝试使用css3进行缩放。看看这把小提琴。

HTML:

<img src="http://lorempixel.com/200/200/sports"/>
<img src="http://lorempixel.com/200/200/nature"/>
<img src="http://lorempixel.com/200/200/city"/>
<img src="http://lorempixel.com/200/200/sports"/>
<img src="http://lorempixel.com/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);
}