JavaScript 实现倒计时代码

来源:互联网 发布:wifi连不上网络 有信号 编辑:程序博客网 时间:2024/05/22 08:04

以下是使用 JavaScript 实现页面动态倒计时的代码:

1. 定义一个 CountDown()  函数计算 天、时、分、秒;

2. 使用 setInterval 对 CountDown() 函数进行调用;

3. 计时结束时使用 clearInterval 停止调用;

由于在页面完全加载后的 一秒才会调用 CountDown()  函数,所以可根据自身要求加上 “window.onload = CountDown;” ,在页面刚加载完就调用此方法,可去除一秒误差。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>JavaScript 实现倒计时</title><script type="text/javascript">var totalTime = 60 * 60 * 24 * 1;// 倒计时总时间,以秒为单位function CountDown() {if (totalTime >= 0) {seconds = Math.floor(totalTime % 60);// 秒minutes = Math.floor(totalTime / 60 % 60);// 分hour = Math.floor(totalTime / 60 / 60 % 24);// 时day = Math.floor(totalTime / 60 / 60 / 24);// 天timerMsg = "距离活动结束还有:" + (day >= 10 ? day : "0" + day) + "天" + (hour >= 10 ? hour : "0" + hour) + "时" + (minutes >= 10 ? minutes : "0" + minutes) + "分" + (seconds >= 10 ? seconds : "0" + seconds) + "秒";document.all["timer"].innerHTML = timerMsg;if (totalTime == 5 * 60) {alert('注意,还有5分钟!');}-- totalTime;} else {clearInterval(timer);// 停止调用函数alert("时间到,计时结束!");}}timer = setInterval("CountDown()", 1000);// 以毫秒为单位,每 1 秒调用一次 CountDown()// window.onload = CountDown;// 页面刚加载完就开始计时</script></head><body><div id="timer" style="color:red; font-weight:bold;">倒计时马上开始……</div></body></html>


0 0