在hover时替换图像

我有一个白色文字“天使”的图像。 每当我把鼠标放在它上面时,我需要用红色替换它。

  $("#angelWord").hover(function(){ $("#angelWord").replaceWith(''); }, function(){ $("#angelWord").replaceWith(''); }); ` 

我不知道为什么,但它不起作用。 图像变成红色,但当我将鼠标移出时,它会保持红色。 我也尝试过鼠标hover,但它也没有给我带来任何结果:

 $("#angelWord").mouseover(function(){ $("#angelWord").replaceWith(''); }); $("#angelWord").mouseout(function(){ $("#angelWord").replaceWith(''); }); 

试试这个:

 $('#angelWord').hover(function() { $(this).attr("src", "img/angel_word_red.gif"); }, function() { $(this).attr("src", "img/angel_word.gif"); }); 

干杯!

尝试使用mouseentermouseleave 。 当光标首先hover元素并且它分别超出元素的边界时,它会被触发。

尝试使用缓存图像的css background ,避免在每个hover时从服务器请求图像; :hover

HTML

  

CSS

 #angelWord { width:50px; height:50px; background:url(img/angel_word.gif); } #angelWord:hover { background:url(img/angel_word_red.gif); } 
 #angelWord { width:50px; height:50px; background:url(http://lorempixel.com/50/50/nature); } #angelWord:hover { background:url(http://lorempixel.com/50/50/cats); } 
  

这是行不通的,因为您将hover处理程序绑定到现有的标记,但是一旦用其他标记替换它,新的标记就不再具有这些处理程序了。

您可以使用递归重新绑定hover处理程序,但更简单的jQuery答案将是使用.attr()函数并仅更改src属性。

 $('#angelWord').hover( function () { //In $(this).attr('src', 'img/angel_word_red.gif'); }, function () { //Out $(this).attr('src', 'img/angel_word.gif'); } ); 

function示例: http : //jsfiddle.net/hiljusti/bt1ns62o/2/

如果CSS3是一个选项,你也可以使用CSS处理它。 ( 是否可以在CSS中设置img标记的src属性的等价物? )

至少在发布时,每个现代浏览器都不支持CSS解决方案。