JS案例之3——倒计时
利用简单的数字累加循环模拟倒计时的效果,逻辑比较简单。如果大牛们有更好的办法欢迎补充。
这种效果经常用于在规定的时间做某件事。比如在1分钟之后重新发送验证码等。
案例演示:
源代码如下:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" Content="text/html; charset=utf-8;"> 5 <title> JS实现倒计时 </title> 6 <meta name="author" content="rainna" /> 7 <meta name="keywords" content="rainna's js lib" /> 8 <meta name="description" content="JS实现倒计时" /> 9 <style> 10 *{margin:0;padding:0;} 11 12 .m-time{width:500px;margin:100px auto;} 13 .m-time .btn,.m-time .btn2{display:block;width:200px;height:40px;margin:10px 0;background:#B4D174;border-radius:5px;color:#fff;text-decoration:none;text-align:center;line-height:40px;} 14 .m-time .btn2{opacity:.3;} 15 .m-time span{font-weight:bold;color:#f00;} 16 </style> 17 </head> 18 <body> 19 <div class="m-time"> 20 <p>请输入倒计时时间:<input type="text" id="timeIpt"/></p> 21 <a href="" class="btn" id="sendBtn">发送</a> 22 <p>剩余<span id="leftTime"></span>秒</p> 23 </div> 24 25 <script> 26 var timer = function(){ 27 var setTime = function(){ 28 var self = this; 29 if(!(self instanceof setTime)){ 30 return new setTime(); 31 } 32 self.sendBtn = document.getElementById('sendBtn'); //发送按钮 33 self.leftTime = document.getElementById('leftTime'); //显示剩余时间 34 self.status = true; //当为true时,发送按钮可点击 35 }; 36 setTime.prototype = { 37 constructor: setTime, 38 showTime: function(time){ 39 var self = this; 40 if(!!self.timerId) clearTimeout(self.timerId); 41 self.timerId = setTimeout(function(){ 42 self.showTime(time); 43 },1000) 44 45 self.leftTime.innerText = time; 46 self.sendBtn.className = 'btn2'; 47 self.status = false; 48 time--; 49 50 //倒计时结束 51 if(time < 0){ 52 clearTimeout(self.timerId); 53 self.status = true; 54 self.sendBtn.className = 'btn'; 55 } 56 }, 57 init:function(){ 58 var self = this; 59 self.sendBtn.onclick = function(event){ 60 event.preventDefault(); 61 if(self.status == true) self.showTime(document.getElementById('timeIpt').value); 62 } 63 } 64 } 65 66 return function(){ 67 var st = new setTime(); 68 st.init(); 69 } 70 }(); 71 72 timer(); 73 </script> 74 </body> 75 </html>