2012-06-21 93 views
1

工作这是HTML我有:jQuery的鼠标悬停不如预期

<div id="social"> 
    <a href="#" class="twitter"><span class="text">Twitter</span></a> 
</div> 

我打算做的是最初隐藏span.text,当我将鼠标悬停在图像中的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"); 
}); 

但发生的事情是,当我将鼠标悬停在它不断显示和隐藏的文本图像..我要去哪里错了?

+0

使用.hover而不是.mouseover事件。检查此链接http://stackoverflow.com/questions/1116361/jquery-hover-mouse-out –

+0

@BishnuPaudel在这里使用'mouseover'和'mouseout'没有任何错误。 – iambriansreed

回答

2

你有一个非常普遍的问题,当跨度显示,鼠标的没有任何更多过一个,所以mouseout事件被调用。

来解决这个使用了mouseenter和鼠标离开事件

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

fiddle for you :D

,并在CSS的意见与/* */而不是与//

+0

Awseome!按预期工作...另一个教训:)谢谢 – Codename

+0

不客气。在我找到它之前,这是一个令人头疼的问题。 id建议你阅读关于mouseenter和mouseleave的文档。 – Jarry

+0

还有一个问题......该解决方案工作正常,但当我将鼠标悬停在图像上时,文本瞬间显示出来。隐藏功能将文本滑动到底部角落,但不是mouseenter功能。我怎样才能让mouseenter函数在文本中滑动? – Codename

1

在你的CSS:

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

//不是征求意见的有效标志。

他们必须被包裹在/* */像:

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

对,对不起。我只为这篇文章添加了评论。 – Codename

0

你并不需要(和不应该'吨)使用JavaScript的这种效果。你可以用CSS来做到这一点,它更干净,更语义:)。例如:

​a.twitter { 
    display: block; 
    width: 300px; 
    height: 300px; 
    background: url('http://www.simplyzesty.com/wp-content/uploads/2012/01/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/

+0

很抱歉,我想我没有清楚地解释自己。最初只有twitter图标可见,当您悬停时,我希望文本能够滑入,即图标应该移动到左边,以显示文本。 – Codename

0

尝试使用mouseleave。 Re mouseout:

此事件类型可能会导致许多由于事件冒泡而引起的头痛。对于 实例,当鼠标指针移出 这个示例中的鼠标指针时,将向其发送一个鼠标移出事件,然后将 滴入Outer。这可以在不合时宜的 时间内触发绑定的鼠标移出处理程序。请参阅.mouseleave()的讨论以获得有用的替代方法。