一、功能描述javascript
當用戶想要獲取驗證碼時,就點擊 免費獲取驗證碼 ,而後開始倒計時,倒計時期間按鈕文字爲剩餘時間x秒,且不可按狀態,倒計時結束後,按鈕更改成點擊從新發送。css
二、分析html
必須用到定時器。按鈕點擊後,在定時器內作出判斷。倒計時60秒,到0結束。java
三、代碼實現:this
重點介紹:定時器在進行下一次倒計時以前,必定要清除一下,這樣的話保證下一次定時器倒計時是正常的。spa
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{margin: 0;padding: 0;} .send{ width:250px; margin:0 auto; } .send input{ display: block; width:200px; font:400 16px/30px "微軟雅黑"; outline: none; border: none; } .send button{ height:30px; border: none; outline: none; font:400 16px/30px "微軟雅黑"; text-align: center; } </style> <script type="text/javascript"> window.onload=function(){ var button=document.getElementsByTagName("button")[0]; button.innerText="免費獲取驗證碼"; var timer=null; button.onclick=function(){ clearInterval(timer);//這句話相當重要 var time=6; var that=this;//習慣 timer=setInterval(function(){ console.log(time); if(time<=0){ that.innerText=""; that.innerText="點擊從新發送"; that.disabled=false; }else { that.disabled=true; that.innerText=""; that.innerText="剩餘時間"+(time)+"秒"; time--; } },1000); } } </script> </head> <body> <div id="send"> <input type="text" name="in" id="in" value="" /><button></button> </div> </body> </html>