代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" name="" id="txt"> <button id="btn">点我获取验证码</button>
<script>
var btn = document.getElementById('btn');
var num = 60;
var timer = null;
btn.onclick = function () {
clearInterval(timer); // 先清掉上次所有定时器 保证 按下按钮时 只开启当前定时器
timer = setInterval(function () {
num--;
if (num < 0) {
num = 5;
btn.innerHTML = '点我获取验证码'
clearInterval(timer);
btn.disabled = false; // 恢复按钮点击状态
return false;
}
btn.innerHTML = num + 's之后再获取';
btn.disabled = true; // 设置按钮禁止点击状态
}, 1000)
}
</script>
</body>
</html>
效果