jQuery倒计时器

目前我有这个代码

setTimeout(function() { $('#hideMsg').fadeOut('fast'); }, 2000); 

我可以把倒数计时器放2秒吗?

喜欢

 
The entry you posted not valid. This Box will Close In 2 Seconds

“此框将在2秒后关闭”将自动更改为2秒1秒

使用setInterval而不是setTimeout ,然后使用clearInterval的组合

 var sec = 2 var timer = setInterval(function() { $('#hideMsg span').text(sec--); if (sec == -1) { $('#hideMsg').fadeOut('fast'); clearInterval(timer); } }, 1000); 

HTML

 
The entry you posted not valid. This Box will Close In 2 Seconds

疯狂的演示


让它变得更好。

 var sec = $('#hideMsg span').text() || 0; var timer = setInterval(function() { $('#hideMsg span').text(--sec); if (sec == 0) { $('#hideMsg').fadeOut('fast'); clearInterval(timer); } }, 1000);​ 

所以时间将取决于 。 例如, 2为2秒, 5为5秒, 60为1分钟。

另一个疯狂的演示

注意:

在我阅读他的回答之前,我没有意识到这与Reigel的答案有多相似。 基本上,唯一的区别是我使用.delay()来隐藏div而不是间隔。 不同的选择……


如果您将初始数字放在 ,那么无论该数字是多少,它都会倒数到零:

 $(function() { // Number of seconds counter starts at is what's in the span var timer, counter = $("#hideMsg span").text(); // Delay the fadeout counter seconds $('#hideMsg').delay(counter * 1000).fadeOut('fast'); // Update countdown number every second... and count down timer = setInterval(function() { $("#hideMsg span").html(--counter); if (counter == 0) { clearInterval(timer)}; }, 1000); });​ 

jsFiddle示例

这使用了jQuery的原生.delay() ,它使用了一个setInterval() ,当它变为零时停止。

在一秒钟后执行另一个设置超时并设置div的.html(),如下所示:

 setTimeout(function() { $('#hideMsg').html('The entry you posted not valid. 
This Box will Close In 1 Second'); }, 1000);

把它们放在一个函数中并运行函数onload,如下所示:

  

希望这可以帮助。