毫秒倒计时小Demo

Demo截图:

Demo:Demo

上代码:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>
 6     </title>
 7     <style>
 8         
 9         *{ margin:0;padding:0; }
10          
11         .timer{
12             width: 200px;
13             margin:0 auto;
14             font-family: 'Microsoft Yahei';
15             font-size: 18px;
16             line-height: 30px;
17         }
18         .timer span{
19             color: #ff556b;
20         }
21         .timer strong{
22 
23         }
24         
25         
26     </style>
27     <script>    
28     window.onload = function(){
29 
30         var oTimer = document.getElementById('timer'),
31               oBtn = document.getElementById('btn'),
32               oSpan = oTimer.getElementsByTagName('span')[0];
33 
34           var timers = setCountdown(oSpan,10,callFn);    
35 
36           
37           oBtn.onclick = function(){
38             clearInterval( timers );
39           };
40           
41           function callFn(){
42             alert( '倒计时结束了~~' );
43           }
44 
45           function setCountdown( obj,num,callBack ){
46             var timer = null;      //定时器;
47             var nums = num * 1000; //时间转化成毫秒;  
48             obj.innerHTML = num;  //对象赋值;
49 
50             timer = setInterval(function(){
51 
52               nums = nums - 100; //每次减100毫秒;
53 
54               if( nums <= 0 ){
55 
56                 callBack();
57 
58                 clearInterval( timer );
59 
60               }
61 
62               obj.innerHTML = parseFloat(nums/1000).toFixed(1);
63 
64             },100);
65 
66             return timer;
67 
68           }
69 
70     }
71     </script>
72 </head>
73 <body>
74     <div id="timer" class="timer" >
75         <div>
76             <span>
77             </span>
78             <strong>
79 80             </strong>
81         </div>
82         <input type="button" id="btn" value="点我">
83     </div>
84         
85 </body>
86 </html>
View Code

后记:

1秒1000毫秒;

所以定时器100毫秒为间隔10次1000(1秒),每次减也是100;

posted @ 2015-10-13 11:39  uustoboy  阅读(733)  评论(0编辑  收藏  举报