如果用户在输入字段中单击,则jQuery停止setTimeout

我有以下jQuery函数:

 $(function() { // setTimeout() function will be fired after page is loaded // it will wait for 5 sec. and then will fire // $("#successMessage").hide() function setTimeout(function() { $("#subscribe-floating-box").animate({"height": "toggle"}, { duration: 300 }); }, 3000); });   function ShowHide(){ $("#subscribe-floating-box").animate({"height": "toggle"}, { duration: 300 }); }  

我也有以下forms:

 

最后,还有一个打开表单的“按钮”(图像)。 该按钮具有以下代码:

 <img src="https://stackoverflow.com/questions/12468122/jquery-stop-settimeout-if-user-clicks-in-input-field//library/images/email-signup-button.png" style="position:relative; top:-146px;" /> 

(请忽略内联CSS – 这是我的工作草案)。

换句话说,我有一个电子邮件注册按钮,可以打开订阅表单。 最初显示此表单,但是通过setTimeout函数在3000时间间隔后关闭,并在用户单击email-signup-button.png图像时回调。 点击后回拨后,3000后将不再自动隐藏。

我需要的是:如果观众在电子邮件输入字段内点击,是否可以停止setTimeoutfunction? 他不必开始输入任何内容,只需点击内部即可。 如果他决定将电子邮件地址放入,我不希望该表格关闭。尽管有人在访问该网站时不可能立即去写她/他的电子邮件,我想消除这种可能性。

您需要捕获setTimeout的id并清除它:

 var id = setTimeout(function(){alert('hi');}, 3000); clearTimeout(id); 

这个的实现看起来像这样:

 var timeoutId = setTimeout(function() { $("#subscribe-floating-box").animate({"height": "toggle"}, { duration: 300 }); }, 3000); $('#subscribe-field').focus(function(){ clearTimeout(timeoutId); }); 

您可以使用

 var timer=setTimeout(...); 

当你想要阻止它时,请使用

 clearTimeout(timer); 

我有点慢,因为我做了http://jsfiddle.net/2tdL9/但是每个人都是正确的clearTimeout()就是答案

ShowHide()函数更改为:

 function ShowHide(){ window.eto = setTimeout(function() { $("#subscribe-floating-box").animate({"height": "toggle"}, { duration: 300 }); }, 3000); } 

并且输入电子邮件的onclick处理程序如下所示:

 onclick="clearTimeout(window.eto);if ( this.value == 'Email Address' ) { this.value = ''; }" 

那应该是你想要的。