我有一个图像文件夹。在这个文件夹中,我有两种类型的几张图像;一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");
});
它有效,但我不喜欢我重复事情的方式。有什么办法可以提高效率吗?
Thanks
我会说,使用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()
. You 不需要 regex
对于这个简单的替换:
$(".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"));
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)