jQuery-悬停时替换图片 [英] JQuery - replace image on hover

查看:67
本文介绍了jQuery-悬停时替换图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图像文件夹.在此文件夹中,我有几种两种类型的图像:一个png和一个gif.显示的图像是png版本.在图像悬停时,我需要将其替换为其gif版本.悬停后,将png版本放回原处.

I have an images folder. Within this folder, I have several images of two types; one png and one gif. The displayed image is the png version. On an image hover, I need to replace it with its gif version. And when hover is out, put the png version back in place.

我目前有以下可行的方法

I currently have the following which works

$(".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");
});

它有效,但是我不喜欢重复的方式.有什么方法可以提高效率?

It works, but I dont like the way I am repeating things. Is there any way to make this more efficient?

谢谢

推荐答案

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

I would say, use data-* attributes in a better way. I would suggest you to have something like this:

<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().您不需要 regex进行此简单替换:

Or in short, you can also use .replace(). You don't need regex for this simple replacement:

$(".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-悬停时替换图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆