JS案例之3——倒計時
原始碼如下: 複製代碼 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>