2012-02-07 98 views
0

我有這樣的腳本:jQuery的延遲鼠標移出

$("#menu ul li").mouseover(
    function() { 
     $(this).find(".submenu").fadeIn("slow"); 
    } 
); 

var timer = 0; 
function animate_me() { 
    $(this).find(".submenu").stop().fadeOut("slow"); 
} 
$(function(){ 
    $("#menu ul li").mouseout(function(){ 
     timer = setTimeout("animate_me()", 300); // start timer when mouse is moved in 
    }, function() { 
     clearTimeout(timer); // stop it if mouse is moved out 
    }); 
}); 

我如何延緩淡出,直到菜單UL裏已經打探過兩秒鐘?

回答

2

所有的鼠標,mouseout,只有一個參數。如果你想以這種方式使用它,你需要使用.hover()。然後,你可以只使用.dealy()來實現自己的目標,.stop(true,true)將清除延遲

這裏是一個演示: http://jsfiddle.net/meo/zTTFJ/

+0

延遲只會延遲淡出 - 我需要它停止函數,如果再次註銷 – maccaj51 2012-02-07 12:43:25

+0

如果您使用true作爲第一個參數在'.stop()'它停止延遲也...試試演示... – meo 2012-02-07 12:46:55

3

使用HoverIntent plugin for jQuery。它完全符合你的需求和更多。

具體而言,超時功能提供此功能。實例:

function showIt() { $(this).find(".submenu").fadeIn("slow"); } 
function hideIt() { $(this).find(".submenu").stop().fadeOut("slow"); } 

$("#menu ul li").hoverIntent({ 
    over: showIt, 
    out: hideIt, 
    timeout: 300 /*ms*/ 
}); 

從文檔

超時

一個簡單的延遲,以毫秒爲單位的 「出」 功能之前被調用。 如果用戶在超時之前將鼠標置於元素上,則 過期,則不會調用「out」函數(也不會調用「over」 函數)。這主要是爲了防止馬虎/人類暫時(無意)將 用戶從目標元素上移開的移動軌跡......讓他們有時間返回。默認 超時:0

+0

它的一個很好的評論,但它是一個答案? – meo 2012-02-07 12:50:05

+0

這是一個答案,使用插件,解決了問題。 – 2012-02-07 12:50:41

+2

我不想得到一個鏈接到一個插件作爲一個具體問題的答案... – meo 2012-02-07 12:53:41