2010-08-10 49 views
2

後,我有一個dropUp菜單如下:jQuery函數的setTimeout

$(document).ready(function(){ 
var opened = false; 
$("#menu_tab").click(function(){ 
    if(opened){ 
     $("#menu_box").animate({"top": "+=83px"}, "slow"); 
     setTimeout(function(){ 
       $("#menu_box").animate({"top": "+=83px"}, "slow"); 
       }, 2000); 
       clearTimeout(); 
    }else{ 
     $("#menu_box").animate({"top": "-=83px"}, "slow"); 
    } 
    $("#menu_content").slideToggle("slow"); 
    $("#menu_tab .close").toggle(); 
    opened = opened ? false : true; 
}); 
}); 

所以點擊menu_tab後,菜單下降並保持,直到再次點擊,但我想超時使說2秒後菜單再次下降。

我明顯得到了編碼錯誤,因爲超時無效。任何幫助,將不勝感激! TIA。

回答

1

我認爲你正在嘗試做這樣的事情:

試試看:http://jsfiddle.net/YFPey/

var opened = false; 
var timeout; 
$("#menu_tab").click(function() { 
     // If there's a setTimeout running, clear it. 
    if(timeout) { 
     clearTimeout(timeout); 
     timeout = null; 
    } 
    if(opened) { 
     $("#menu_box").animate({"top": "+=83px"}, "slow"); 
    } else { 
     $("#menu_box").animate({"top": "-=83px"}, "slow"); 
      // Set a timeout to trigger a click that will drop it back down 
     timeout = setTimeout(function() { 
      timeout = null; 
      $("#menu_tab").click(); 
     }, 2000); 
    } 
    $("#menu_content").slideToggle("slow"); 
    $("#menu_tab .close").toggle(); 
    opened = !opened; 
});​ 
+0

肯定是!非常感謝! – circey 2010-08-10 04:06:26

0

您在這裏使用clearTimeout()是錯誤的。當你用setTimeout()創建定時器時,你需要傳遞一個對返回ID的引用。

不能說,如果這是造成你的問題,雖然(它可能不是)。如果你在Javascript錯誤控制檯中得到任何可能有用的信息。該站出來給我

0

兩件事情:

  1. 因爲opened開始爲假,計時器只得到啓動的第二次點擊。
  2. 在定時器處理程序中,你應該更新opened