用戶點擊「獲取驗證碼」→ 按鈕禁用並顯示倒計時 (如「60秒後重新發送」)→ 倒計時結束恢復可點擊狀態。防止短信/郵件接口被濫用。
<input type="button" id="btn" value="免費獲取驗證碼" onclick="settime(this)" />
<script>
var countdown = 60;
function settime(btn) {
if (countdown === 0) {
btn.removeAttribute("disabled");
btn.value = "免費獲取驗證碼";
countdown = 60;
return;
}
btn.setAttribute("disabled", "disabled");
btn.value = "重新發送(" + countdown + ")";
countdown--;
setTimeout(function() { settime(btn); }, 1000);
}
</script>
<input type="button" id="btn" value="免費獲取驗證碼" />
<script>
var wait = 60;
var timer = null;
var btn = document.getElementById('btn');
btn.onclick = function() {
if (timer) return; // 防止重複點擊
timer = setInterval(function() {
if (wait === 0) {
btn.removeAttribute("disabled");
btn.value = "免費獲取驗證碼";
wait = 60;
clearInterval(timer);
timer = null;
} else {
btn.setAttribute("disabled", "disabled");
btn.value = wait + "秒後可以重新發送";
wait--;
}
}, 1000);
};
</script>
class CountdownButton {
constructor(buttonEl, options = {}) {
this.btn = buttonEl;
this.seconds = options.seconds || 60;
this.onText = options.onText || "免費獲取驗證碼";
this.offText = options.offText || "{sec}秒後重新發送";
this.onClick = options.onClick || (() => {}); // 實際發送驗證碼邏輯
this.timer = null;
this.remaining = this.seconds;
this.btn.addEventListener('click', this.handleClick.bind(this));
}
handleClick() {
if (this.timer) return;
this.onClick().then(() => this.startCountdown()).catch(() => {
// 發送失敗:立即恢復
this.reset();
});
}
startCountdown() {
this.btn.disabled = true;
this.updateText();
this.timer = setInterval(() => {
this.remaining--;
if (this.remaining <= 0) this.reset();
else this.updateText();
}, 1000);
}
updateText() {
this.btn.value = this.offText.replace('{sec}', this.remaining);
}
reset() {
clearInterval(this.timer);
this.timer = null;
this.remaining = this.seconds;
this.btn.disabled = false;
this.btn.value = this.onText;
}
destroy() {
this.reset();
this.btn.removeEventListener('click', this.handleClick.bind(this));
}
}
// 使用
new CountdownButton(document.getElementById('btn'), {
seconds: 60,
onClick: () => fetch('/api/send-sms', {method:'POST', body:JSON.stringify({phone: '13800000000'})})
.then(r => r.ok ? Promise.resolve() : Promise.reject())
});
前端倒計時**只能阻擋誠實用戶**,惡意腳本可繞過。必須在後端實施:
<button id="btn" aria-live="polite">免費獲取驗證碼</button>
JS 中更新 `btn.textContent` 即可自動播報。