2011-12-12 25 views
5

我有一段代碼,基本上是說:如果你翻身這一點,那麼其他的事情出現,如果你推出接着它會消失。如何防止鼠標進入/離開發生過很多次

的問題是,如果我把鼠標和滾動輸入/輸出次數太多則(因爲我錯誤地創造了很多的事件它)的元素出現/消失過很多次

我的代碼看起來像這樣:

$('div.accordionContent').mouseenter(function() 
{ 
    $(this).find(".something").animate({left: 0}, 300)}).mouseleave(function() { 
    $(this).find(".something").animate({ 
    left: -200}, 500);; 
}); 

如何告訴它以避免多次懸停?

我使用jQuery 1.4.3是否有幫助..

回答

5

而不是避免多次觸發,嘗試啓動另一個之前停止動畫。

$('div.accordionContent').mouseenter(function() { 
    $(this).find(".something").stop().animate(...) 
}); 
+0

不錯的選擇!即使我已經在我的代碼中實現了相同的功能。 – Murtaza

+0

在我的情況下,我沒有使用動畫(只是添加/刪除類名),因此不能使用「停止」。任何解決方案? – apnerve

1

問題是你在舊的完成之前激發新的事件。爲了防止這種情況發生,您可以在當前事件完成其任務之前停止監聽(刪除監聽器)以供將來的事件使用。

0

jQuery.animate有一個選項「隊列」。如果你設置爲false,我認爲這個事件不會觸發太多。我認爲=)

0

如果你想這樣做的正確的方法,我的建議是

$('div.accordionContent').bind('mouseenter mouseleave', function(e){ 

    var $something = $(this).find(".something"); 

    if(e.type == 'mouseenter'){ 
     $something.animate({left:0}, {queue:false, duration:300 }); 
    } else { 
     $something.animate({left:-200}, {queue:false, duration:500 }); 
    } 
}); 
0

你可以試試這個:

$('div.accordionContent').mouseenter(function(){ 
    var div = $(this); 
    clearTimeout(window.me); 
    window.me = setTimeout(function(){ 
     div.find(".something").animate({left: 0}, 300)}).mouseleave(function(){ 
      $(this).find(".something").animate({ 
      left: -200}, 500); 
     }); 
    },50); 
}); 

這裏的想法是取消當前的mouseenter如果50個延遲尚未達到。

相關問題