setTimeout之后的jquery函数

时间:2010-08-10 03:05:24

标签: jquery settimeout

我有一个dropUp菜单,其中包含以下内容:

$(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。

3 个答案:

答案 0 :(得分: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;
});​

答案 1 :(得分:0)

你在这里使用clearTimeout()是错误的。您需要传递对使用setTimeout()创建该计时器时返回的ID的引用。

不能说这是否会导致你的问题(可能不是)。如果你在Javascript错误控制台中得到任何可能有帮助的东西。

答案 2 :(得分:0)

有两件事让我感到高兴:

  1. 由于opened开头为false,因此定时器仅在第二次点击时启动。
  2. 在计时器处理程序中,您是否应该更新opened
相关问题