註冊時往往需要發送驗證郵件,為了避免重複發送,可以在點擊「發送」後讓按鈕暫時禁用,倒計時結束再恢復可點擊。下面是一個簡單例子:
<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>
原理並不複雜:點擊後把 wait 設為 60,通過 setAttribute("disabled", true) 禁用按鈕,並用 setTimeout 每秒遞減一次、同步更新按鈕文字;當 wait 減到 0 時,移除 disabled 屬性、恢復按鈕文字並重置計時。這樣就能兼顧用戶體驗與防止重複提交。