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

时间:2018-07-13 02:08:55

标签: javascript 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>

1 个答案:

答案 0 :(得分:0)

您实际上可以使用普通CSS来做到这一点,这样会更加有效。

只需创建一个div,将两个图像都放置在绝对位置内,这样一个图像就可以放在另一个图像的顶部,并且在悬停时应用不透明度:0,并转换为前图像。

您可以使用绝对位置,z-index和悬停伪选择器来实现。

<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>
sa