JQuery – 在hover时替换图像

我有一个图像文件夹。 在这个文件夹中,我有两种类型的图像; 一个和一个gif 。 显示的图像是png版本。 在图像hover时,我需要用它的gif版本替换它。 当hover时,将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-*属性。 我建议你有这样的事情:

  

在jQuery中:

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

或者简而言之,您也可以使用.replace() 。 这个简单的替换你不需要 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")); }); 

如果您将选择器展开为包含img ,则可以使用$(this)来引用它。 如果你只是用png替换gif (反之亦然),那么使用正则表达式很容易做到这一点。

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

编辑 :请同时参阅Praveen Kumar的答案 ,以获得在data-属性中声明文件名的好建议。

另一个解决方案,

您还可以使用事件处理程序委派并将参数传递给它。

例如

 function replaceImageHandler(ev) { var $img = $(this).find('img'); var imgSrc = $img.attr('src'); var toImg = imgSrc.substring(0, imgSrc.lastIndexOf(".")) + '.' + ev.data.ext; $img.attr('src', toImg) } $(".image-container") .on('mouseover', { ext: 'gif'}, replaceImageHandler) .on('mouseout', { ext: 'png'}, replaceImageHandler); 

如果要附加更多事件处理程序,也可以执行此操作。

例如

 function replaceImageHandler(ev) { var $img = $(this).find('img'); $img.attr('src', ev.data.src); } $(".image-container") .on('click', { src: 'zoom-my-image.gif'}, replaceImageHandler) .on('mouseover', { src: 'my-image-1.gif'}, replaceImageHandler) .on('mouseout', { src: 'my-image-2.png'}, replaceImageHandler); 

使用css :hover

 .image-container { display:block; width: 50px; height: 50px; background: url(http://lorempixel.com/50/50/nature) , url(http://lorempixel.com/50/50/cats); background-size: 100% 100%, 0% 0%; } .image-container:hover { background-size: 0% 0%, 100% 100%; } 
 

通过css实现这个的更好方法

 .image-container:hover{ url: imagepath; }