简体   繁体   English

click()和setTimeout问题

[英]click() and setTimeout issue

I have a message panel at the bottom of my page which I display by applying a negative margin. 我在页面底部有一个消息面板,该面板通过应用负边距显示。 When it opens, I would like it to either (whichever first): 当它打开时,我希望它(以先到者为准):

  1. Close when user clicks on #panel-close (this is on the panel, so only visible when it is open) 当用户单击#panel-close时关闭(位于面板上,因此仅在打开时可见)

    OR 要么

  2. Close after 6 seconds 6秒后关闭

The code I have works until I start opening and closing it repeatedly - then the timing goes wrong. 我拥有的代码会一直起作用,直到我开始反复打开和关闭它-然后时间错了。 I believe I need to cancel the setTimeout if i have closed the panel with a click, but i can't get this to work. 我相信如果我单击一下关闭了面板,就需要取消setTimeout,但是我无法使它起作用。

$("#button").click(function() {
    messagePanel.animate({
        marginTop: '-50px' //open
    }, 600 );

    setTimeout(function(){
        messagePanel.animate({
            marginTop: '0px' //close
        }, 600 );
    },6000)

});

$('#panel-close').click(function() {
    messagePanel.animate({
        marginTop: '0px' //close
    }, 600 );
});

Any help appreciated! 任何帮助表示赞赏!

If you need to cancel the setTimeout event, you need to get the timeoutID return by setTimeout function, eg. 如果需要取消setTimeout事件,则需要通过setTimeout函数获取timeoutID返回。

var timeoutId;
timeoutId = setTimeout(function () {...});
$('#panel').click(function() {
   clearTimeout(timeoutId);
}

see https://developer.mozilla.org/en/DOM/window.clearTimeout for more detail 有关更多详细信息,请参见https://developer.mozilla.org/en/DOM/window.clearTimeout

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM