2012-07-16 77 views
2

如何在下拉菜單中設置時間或延遲5秒鐘。如何在下拉菜單中設置5秒的時間或延遲?

要求如下:當某人將鼠標懸停在主菜單上時,僅當鼠標遠離主菜單或子菜單時,才顯示子菜單5秒。

現在我已經增加了高達標高圖像的高度,以便它不會被隱藏,直到您將鼠標移出該標題區域。

下面是該網站的鏈接:http://transitions.advisorproducts.com/home

,這是一個參考站點鏈接:http://focusyou.com/home(我的要求是這樣的,但我不希望複製該代碼,我想在我自己的代碼來實現)

以下是JS:

$(function() 
{ 
    $("ul.dropdown li").hover(function() 
    { 
     $(this).addClass("hover"); 
     $('ul:first',this).css('visibility', 'visible'); 
    }, function() 
    { 
     $(this).removeClass("hover"); 
     $('ul:first',this).css('visibility', 'hidden'); 
    }); 
    $("ul.dropdown li ul li:has(ul)").find("a:first").append(" » "); 
}); 

感謝提前:)

您可以測試在這裏:http://jsfiddle.net/alokjain_lucky/KQAYT/2/

+2

你知道['setTimeout'(https://developer.mozilla.org/en/DOM/window.setTimeout)? – 2012-07-16 07:38:19

+0

你知道setTimeout(); – mfadel 2012-07-16 07:38:40

回答

2

試試這個:

$(function() 
{ 
    var timer = 0; 
    $("ul.dropdown > li").hover(function() 
    { 
     if (timer) clearTimeout(timer); 
     $("ul.dropdown > li").removeClass("hover"); 
     $("ul.dropdown > li ul").css('visibility', 'hidden'); 
     $(this).addClass("hover"); 
     $('ul:first',this).css('visibility', 'visible'); 
    }, function() 
    { 
     var link = $(this); 
     timer = setTimeout(function(){ 
      $(link).removeClass("hover"); 
      $('ul:first',link).css('visibility', 'hidden'); 
     }, 5000); 
    }); 
    $("ul.dropdown li ul li:has(ul)").find("a:first").append(" » "); 
}); 
  1. setTimeout的功能將添加一個延遲毫秒指定數量。
  2. 這個關鍵字在setTimeout函數裏面不起作用,所以我在變量鏈接中使用了對這個值的引用。

這裏的代碼的工作示例:http://jsfiddle.net/alokjain_lucky/KQAYT/

+0

令人敬畏的工作Alok :)這是現在工作完美:) – 2012-07-16 09:39:29

+0

這一個是更清晰 - if(timer)clearTimeout(timer); 以前它創造了一點點問題,但現在它的100%完美按照我的要求:) – 2012-07-16 10:11:30

4

如果你想抽象的這種行爲,而不是用定時器等處理,然後使用此:
http://cherne.net/brian/resources/jquery.hoverIntent.html

否則,只用一個定時器:

$(function() 
{ 
    var hideTimer; 
    $("ul.dropdown li").hover(function() 
    { 
     $(this).addClass("hover"); 
     $('ul', this).css('visibility', 'hidden'); //this should fix the error you mentioned! 
     $('ul:first',this).css('visibility', 'visible'); 
    }, function() 
    { 
     if(hideTimer) { 
      clearTimeout(hideTimer); 
      hideTimer = setTimeout(function(){ 
       $(this).removeClass("hover"); 
       $('ul:first',this).css('visibility', 'hidden'); 
      }, 5000); 
     } 
    }); 
    $("ul.dropdown li ul li:has(ul)").find("a:first").append(" » "); 
}); 

我肯定會推薦的jQuery雖然hoverIntent插件,懸停意圖很好的抽象,再加上沒有手動定時器管理。

+0

感謝您的快速回復您的邏輯是完美的,但我認爲他們可能是一些問題的條件,它不工作完美,一旦我懸停菜單,並從該區域刪除鼠標子菜單仍然存在,我認爲隱藏的功能不完美,因爲後懸停在所有的菜單上,所有的子菜單現在都可見。 – 2012-07-16 08:18:51

+0

+1爲hoverintent它的工作方式,人們發現自然 – 2012-07-16 08:52:45

+0

嘿非常感謝:)你的Ans也幫助我很多它是真棒:) – 2012-07-16 14:24:09