JS原生代码之倒计时抢购
刚刚用了一点时间把完善了的倒计时抢购功能又做了一遍,这回用的是原声代码,没有引入jquery库,虽然明显感觉原生代码量要多一些,但是写出来个小功能还是很有成就感的。需要注意的就是代码顺序执行的问题,一定要思路清晰。要不然代码顺序写错,有些功能还是实现不了的。
学到了原声js改变input的disabled的属性值,因为想让倒计时结束的同时,抢购按钮可以被点击。代码为:document.getElementById("buy").disabled = "";或者disabled的值为false也可以。
下面是我编写的代码,哪里不完善,还请大神指点。
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>倒计时抢购</title> 6 </head> 7 <body> 8 <span id="time"></span> 9 <input type="button" value="开始抢购" id="buy" disabled="true"> 10 <script> 11 function Time(){ 12 var date = new Date(); 13 var nowhour = date.getHours(); 14 var nowmin = date.getMinutes(); 15 var nowsec = date.getSeconds(); 16 var finalhour = 22; 17 var finalmin = 22; 18 var finalsec = 22; 19 var finals = finalhour * 3600 + finalmin * 60 + finalsec; 20 var nows = nowhour * 3600 + nowmin * 60 + nowsec; 21 var showhour = parseInt((finals - nows)/3600); 22 var showmin = parseInt((finals - nows)%3600/60); 23 var showsec = (finals - nows)%60; 24 if(showsec<10){ 25 showsec = "0" + showsec; 26 } 27 if(showmin<10){ 28 showmin = "0" + showmin; 29 } 30 if(showhour<10){ 31 showhour = "0" + showhour; 32 } 33 document.getElementById("time").innerHTML = "距离22点22分22秒还有:" + showhour + ":" + showmin + ":" + showsec; 34 if(showhour == "00" && showmin == "00" && showsec =="00"){ 35 clearInterval(t); 36 document.getElementById("buy").disabled=""; 37 } 38 } 39 Time(); 40 var t = setInterval(Time,1000); 41 </script> 42 </body> 43 </html>