2012-06-21 30 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()的討論以獲得有用的替代方法。