當使用者想取得驗證碼時,點擊「免費獲取驗證碼」,隨即開始倒數;倒數期間按鈕文字顯示剩餘秒數且不可點擊,計時結束後按鈕文字改為「點擊重新發送」並恢復可點。
核心一定用得上計時器:按鈕點擊後啟動 timer,在 timer 內部做判斷,從 60 遞減到 0 結束。
重點提醒:在啟動下一次倒數之前,一定要先 clearInterval,否則連續點擊會產生多個 timer 並行,秒數就會亂掉。
<!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>
用 that 保存 this:setInterval 的 callback 裡 this 已不再是按鈕,先把 this 存進 that 才能操作到它。若用箭頭函式寫,this 會自動沿用外層,就不需要這層繞彎。時間從 6 開始只是為了方便看效果,正式環境改成 60 即可。倒數歸零後要記得把 disabled 設回 false,否則按鈕會永久卡死。
另外,這裡用 innerText 直接改按鈕文字,如果按鈕內含圖示或 HTML 結構,應改用 textContent 搭配獨立的 span 來更新數字,避免整個結構被覆蓋掉。