jQuery鼠标hover不按预期工作

这是我的html:

 

我打算做的最初是隐藏span.text,当我将鼠标hover在div背景中的图像上时。 这是我的CSS

 #social a { display:inline-block; overflow:hidden; padding:4px 0 0 28px; /* left padding is for the bg image to be visible*/ } #social a span { display:none; } #social .twitter { background:url(../images/social/twitter.png) no-repeat left top; } #social .twitter:hover { background:url(../images/social/twitter_hover.png) no-repeat left top; } 

这是我的js:

 $("#social a.twitter").mouseover(function(){ $("span",this).show("slow"); }).mouseout(function(){ $("span",this).hide("slow"); }); 

但是当我将鼠标hover在图像上时,它会继续显示并隐藏文本。我在哪里出错?

你有一个非常常见的问题,当跨度显示时,鼠标不再是a,所以mouseout事件被调用。

修复此问题使用mouseenter和mouseleave事件

 $("#social a.twitter").mouseenter(function(){ $("span",this).show("slow"); }).mouseleave(function(){ $("span",this).hide("slow"); });​ 

小提琴:D

并且,在css中,注释使用/* */而不是//

在你的CSS中:

 // left padding is for the bg image to be visible 

//不是评论的有效符号。

它们必须包含在/* */ like中:

 /* left padding is for the bg image to be visible */ 

您不需要(也不应该)使用javascript来实现此效果。 你可以使用CSS,它更干净,更具语义:)。 例:

 ​a.twitter { display: block; width: 300px; height: 300px; background: url('http://sofzh.miximages.com/jquery/twitter_newbird_boxed_whiteonblue2.png'); } a.twitter span { opacity: 0; -webkit-transition: opacity 0.2s; -moz-transition: opacity 0.2s; -o-transition: opacity 0.2s; transition: opacity 0.2s; } a.twitter:hover span { opacity: 1; } 

jsFiddle: http : //jsfiddle.net/Ut4Gx/

尝试使用mouseleave 。 重新输出:

由于事件冒泡,此事件类型可能会导致许多令人头疼的问题。 例如,当鼠标指针在此示例中移出Inner元素时,将向其发送mouseout事件,然后向上逐渐显示为Outer。 这可以在不合适的时间触发绑定的mouseout处理程序。 有关有用的替代方法,请参阅.mouseleave()的讨论。