jQuery倒数计时器 [英] jQuery countdown timer

查看:100
本文介绍了jQuery倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前我有此代码

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

我可以将倒数计时器放置2秒钟吗?

is it possible for me to put countdown timer for 2 seconds?

喜欢

<div id="hideMsg">
The entry you posted not valid.
This Box will Close In 2 Seconds
</div>

此框将在2秒内关闭"会自动更改为2秒1秒

"This Box will Close In 2 Seconds" will automatically change to 2sec 1sec

推荐答案

使用 setInterval 代替 setTimeout ,然后结合使用

use setInterval instead of setTimeout, then with the combination of clearInterval

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

html

<div id="hideMsg">
The entry you posted not valid.
This Box will Close In <span>2</span> Seconds
</div>

疯狂的演示


使它变得更好.

crazy demo


Making it better.

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

,因此时间将取决于<span>内部的内容.例如,<span>2</span>是2秒,<span>5</span>是5秒,<span>60</span>是1分钟.

so that the time will depends on what is inside the <span>. For example, <span>2</span> is 2 seconds, <span>5</span> is 5 seconds, and <span>60</span> is 1 minute.

这篇关于jQuery倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆