gpt4 book ai didi

JQuery - 替换悬停时的图像

转载 作者:行者123 更新时间:2023-11-30 23:47:39 25 4
gpt4 key购买 nike

我有一个图像文件夹。在这个文件夹中,我有两种类型的几张图像;一张 png 和一张 gif。显示的图像是 png 版本。在图像悬停时,我需要将其替换为其 gif 版本。当悬停消失时,将 png 版本放回原位。

我目前有以下有效的方法

$(".image-container").mouseover(function () {
var imgName = $(this).find('img').attr('src');
var img2 = imgName.substring(0, imgName.lastIndexOf("."));
$(this).find('img').attr("src", img2+".gif");
}).mouseout(function () {
var imgName = $(this).find('img').attr('src');
var img2 = imgName.substring(0, imgName.lastIndexOf("."));
$(this).find('img').attr("src", img2+".png");
});

它有效,但我不喜欢我重复事情的方式。有什么办法可以提高效率吗?

谢谢

最佳答案

我想说,以更好的方式使用 data-* 属性。我建议你有这样的东西:

<img src="img.png" data-src="img.png" data-hover="img.gif" alt="" class="image-container" />

在 jQuery 中:

$(".image-container").mouseover(function () {
$(this).attr('src', $(this).data("hover"));
}).mouseout(function () {
$(this).attr('src', $(this).data("src"));
});

或者简而言之,您还可以使用.replace()。您不需要正则表达式来进行这个简单的替换:

$(".image-container").mouseover(function (e) {    
$(this).attr("src", $(this).attr("src").replace(".png", ".gif"));
}).mouseout(function (e) {
$(this).attr("src", $(this).attr("src").replace(".gif", ".png"));
});

关于JQuery - 替换悬停时的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34767900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com