简体   繁体   English

使用淡入淡出在悬停和返回时更改图像

[英]Changing image on hover and back using fade

I'm trying to change an image on hover and back again. 我正在尝试在悬停时更改图像并再次返回。

The idea is that when I hover over an image, it fades into a different image and when my mouse leaves, the image fades back to the original. 这个想法是,当我将鼠标悬停在图像上时,它会淡化为其他图像,而当鼠标离开时,图像会变回原始图像。

Here is what I have tried so far, using jQuery: 到目前为止,这是我使用jQuery尝试过的:

<img src="https://www.shareicon.net/data/128x128/2015/08/17/86675_cat_256x256.png" />

<script>

$("img").hover(function(event) {
    event.preventDefault();
    console.log("hover");

    $("img").fadeOut(400, function() {
        $("img").attr("src", "http://files.softicons.com/download/animal-icons/meow-icon-set-by-iconka/png/128x128/cat_purr.png")
    }).fadeIn(400, function() {
        $("img").attr("src", "https://www.shareicon.net/data/128x128/2015/08/17/86675_cat_256x256.png")
    });
});

</script>

You can actually do this with plain CSS and it would be more efficient. 实际上,您可以使用普通CSS来完成此操作,这样会更加高效。

Just create a div, put both images inside, absolute position so one is on top of another, and when hover apply opacity: 0 with a transition to the front image. 只需创建一个div,将两个图像都放在绝对位置内,这样一个图像就位于另一个图像的顶部,当悬停时,应用不透明度:0并过渡到正面图像。

You can achieve this with position absolute, z-index, and hover pseudo selector. 您可以使用绝对位置,z-index和悬停伪选择器来实现。

 .container{ width: 300px; height: 300px; position: relative; } img{ position: absolute; top: 0; left: 0; } .img-top{ z-index: 999999; transition: 0.3s linear all; } .img-top:hover{ opacity: 0; } 
 <div class="container"> <img class="img-bottom" src="https://www.cesarsway.com/sites/newcesarsway/files/d6/images/askthevet/checklist.jpg" alt=""> <img class="img-top" src="https://i.ebayimg.com/images/g/k2gAAOSwT5tWKhVS/s-l300.jpg" alt=""> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM