DIV CSS 佈局教程網

純 JS 實現重發驗證碼按鈕的倒數計時
編輯:關於JavaScript     

發送驗證碼或激活信的按鈕,通常需要「點擊後冷卻一段時間才能再按」,以避免重複發送。以下提供兩種寫法。

代碼一:inline onclick 寫法

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
</head>
<body>
<input type="button" id="btn" value="免費獲取驗證碼" onclick="settime(this)" />
<script type="text/javascript">
var countdown = 60;
function settime(val) {
    if (countdown == 0) {
        val.removeAttribute("disabled");
        val.value = "免費獲取驗證碼";
        countdown = 60;
    } else {
        val.setAttribute("disabled", true);
        val.value = "重新發送(" + countdown + ")";
        countdown--;
    }
    setTimeout(function () { settime(val); }, 1000);
}
</script>
</body>
</html>

代碼二:以事件綁定觸發

註冊時需要發送激活郵件,同樣要避免重複發送。這裡示範用 onclick 事件註冊而非行內屬性:

<html>
<head>
<title>點擊後按鈕變灰,倒數結束可重複點擊</title>
</head>
<body>
<input type="button" id="btn" value="免費獲取驗證碼" />
<script type="text/javascript">
var wait = 60;
function time(o) {
    if (wait == 0) {
        o.removeAttribute("disabled");
        o.value = "免費獲取驗證碼";
        wait = 60;
    } else {
        o.setAttribute("disabled", true);
        o.value = wait + " 秒後可以重新發送";
        wait--;
        setTimeout(function () { time(o); }, 1000);
    }
}
document.getElementById("btn").onclick = function () { time(this); };
</script>
</body>
</html>

幾個實務上的提醒

計時狀態不要放在全域變數。兩個範例都用全域的 countdown/wait,若頁面上有多個這類按鈕,它們會互相干擾。把倒數封裝成函式即可解決:

function setupCountdown(btn, seconds) {
    let left = seconds;
    const original = btn.value;
    btn.disabled = true;
    btn.value = `重新發送(${left})`;
    const timer = setInterval(() => {
        left--;
        if (left <= 0) {
            clearInterval(timer);
            btn.disabled = false;
            btn.value = original;
        } else {
            btn.value = `重新發送(${left})`;
        }
    }, 1000);
}

用 disabled 屬性而非 setAttribute。btn.disabled = true 比 setAttribute("disabled", true) 更直觀,也更明確地反映元素狀態。

冷卻狀態要記錄在伺服器端。這是最重要的一點:前端的倒數計時只是使用者體驗,使用者重新整理頁面或改寫 JavaScript 就能無限發送。真正的頻率限制必須在後端依帳號或 IP 記錄「上次發送時間」,否則會成為簡訊與郵件資源的濫用入口。

另外,倒數期間記得同時停用表單的送出按鈕,並在倒數結束時把焦點还给驗證碼輸入框,對鍵盤使用者會友善許多。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved