最近做浏览器界面倒计时,用js就实现,两种方式:

一:设置时长,进行倒计时。比如考试时间等等

代码如下:

 1 <html>
 2 <head>
 3 <meta charset="UTF-8">
 4 <title>简单时长倒计时</title>
 5 <SCRIPT type="text/javascript">        
 6             var maxtime = 60 * 60; //一个小时,按秒计算,自己调整!   
 7             function CountDown() {
 8                 if (maxtime >= 0) {
 9                     minutes = Math.floor(maxtime / 60);
10                     seconds = Math.floor(maxtime % 60);
11                     msg = "距离结束还有" + minutes + "" + seconds + "";
12                     document.all["timer"].innerHTML = msg;
13                     if (maxtime == 5 * 60)alert("还剩5分钟");
14                         --maxtime;
15                 } else{
16                     clearInterval(timer);
17                     alert("时间到,结束!");
18                 }
19             }
20             timer = setInterval("CountDown()", 1000);                
21         </SCRIPT>
22 </head>
23 <body>
24 <div id="timer" style="color:red"></div>
25 <div id="warring" style="color:red"></div>
26 </body>
27 </html>

运行结果:

二:设置时间戳,进行倒计时。比如距离活动结束时间等等

代码如下:

 1 <html>  
 2 <head>  
 3     <meta charset="UTF-8">  
 4     <title>js简单时分秒倒计时</title>  
 5     <script type="text/javascript">  
 6         function countTime() {  
 7             //获取当前时间  
 8             var date = new Date();  
 9             var now = date.getTime();  
10             //设置截止时间  
11             var str="2017/5/17 00:00:00";
12             var endDate = new Date(str); 
13             var end = endDate.getTime();  
14             
15             //时间差  
16             var leftTime = end-now; 
17             //定义变量 d,h,m,s保存倒计时的时间  
18             var d,h,m,s;  
19             if (leftTime>=0) {  
20                 d = Math.floor(leftTime/1000/60/60/24);  
21                 h = Math.floor(leftTime/1000/60/60%24);  
22                 m = Math.floor(leftTime/1000/60%60);  
23                 s = Math.floor(leftTime/1000%60);                     
24             }  
25             //将倒计时赋值到div中  
26             document.getElementById("_d").innerHTML = d+"";  
27             document.getElementById("_h").innerHTML = h+"";  
28             document.getElementById("_m").innerHTML = m+"";  
29             document.getElementById("_s").innerHTML = s+"";  
30             //递归每秒调用countTime方法,显示动态时间效果  
31             setTimeout(countTime,1000);  
32   
33         }  
34     </script>  
35 </head >  
36 <body onload="countTime()" >  
37     <div>  
38         <span id="_d">00</span>  
39         <span id="_h">00</span>  
40         <span id="_m">00</span>  
41         <span id="_s">00</span>  
42     </div>  
43 </body>  
44 </html>

运行结果:

版权声明:本文为heizai002原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/heizai002/p/6862418.html