2010-07-25 72 views
20
$('.file a').live('mouseenter', function() { 
    $('#download').stop(true, true).fadeIn('fast'); 
}).live('mouseleave', function() { 
    $('#download').stop(true, true).fadeOut('fast'); 
}); 

我希望mouseenter函數的stop()和延遲1秒。 因此,如果我將鼠標懸停在#download上,fadeIn應該在1秒的延遲後開始。如果我同時將鼠標移出fadeIn不應啓動。找我?延遲()或用stop()超時?

我真的不知道該怎麼做,有什麼想法?

+0

@ user239831 - 你對此有一個突出的問題嗎? – 2010-11-12 13:03:26

回答

25

在這種情況下,您需要使用setTimeout(),因爲.delay()的工作方式(以及您無法取消它)。

$('.file a').live('mouseenter', function() { 
    $.data(this, 'timer', setTimeout(function() { 
     $('#download').stop(true, true).fadeIn('fast'); 
    }, 1000)); 
}).live('mouseleave', function() { 
    clearTimeout($.data(this, 'timer')); 
    $('#download').stop(true, true).fadeOut('fast'); 
}); 

You can give it a try here

如果您使用.delay(),它將爲元素取出下一個動畫,無論您是否早先清除該隊列。所以你需要一個暫停,你可以取消,這是通過手動呼叫setTimeout()並存儲結果$.data(),以便您可以稍後通過clearTimeout()清除。

+2

+1簡潔明瞭的解決方案。 – Tomalak 2010-07-25 12:37:45

+0

非常好。延遲是非常重要的。我仍然知道無法取消這意味着它應該非常小心地使用。這是解決這個問題的好方法。謝謝。 – Jake 2012-06-22 21:58:18

+0

嗨。我在[this jsFiddle](http://jsfiddle.net/GZV5V/84/)中爲'slideDown()'和'slideUp()'嘗試了相同的功能,但效果不佳。你能告訴我我在這裏錯過了什麼嗎?注意:我正在嘗試不使用'hoverIntent()'函數。 – hims056 2013-11-13 05:24:39

3

使用setTimeout函數

$('.file a').live('mouseenter', function() { 
setTimeout(function(){ 
    $('#download').stop(true, true).fadeIn('fast'); 
}, 1000); 
}).live('mouseleave', function() { 
    $('#download').stop(true, true).fadeOut('fast'); 
}); 

的setTimeout指定毫秒後執行的函數內的代碼(在本例1000)。

+1

你還需要存儲/清除該超時,如果你快速懸停進出,它將在200ms內完成fadeOut()(如果它運行的話),然後800ms之後有一個排隊的fadeIn,即使你'不要超過元素。看看這裏看看我的意思:http://jsfiddle.net/nick_craver/T9t6N/要測試,快速懸停並離開鏈接。 – 2010-07-25 12:39:33

0

你可以在不使用延遲事件的情況下在jquery上使用它。

$('.file a').hover(function() { 
    time = setTimeout(function() { 
    $('#download').fadeIn(); 
    },1000); 
},function(){ 
    clearTimeout(time); 
}); 

1000是你的時間,它後$('#下載')將淡入。

4

我一直在尋找的答案類似的問題,我發現.animate()也可以用來處理這個問題,它服從.stop()

這將是這個樣子:

$('.file a').live('mouseenter', function() { 
    $('#download') 
     .stop(true, true) 
     .animate({opacity:0}, 1000);   // one second delay 
     .animate({opacity:1}, 'fast', 'swing'); 
}).live('mouseleave', function() { 
    $('#download') 
     .stop(true, true) 
     .animate({opacity:0}, 'slow', 'swing'); 
});