说明:
验证码倒计时是登录注册页面常用的一种方式,今天我将他实现为以后的毕设进行相应的准备!
实现例子代码:
<body>
<input id="txt" type="text">
<input class="btn" type="button" value="发送">
<script>
// 注册点击事件
const btn = document.querySelector('.btn');
btn.onclick = function() {
// 获取验证码input框的id属性的值
const input = document.querySelector("#txt").value;
// console.log(input);
// 验证码开始验证是否符合规则;
const exp = /^\d{6}$/g; //6位有效数字(可以是4位等等,只需要更改花括号的之即可)
const isExp = exp.test(input); //验证 是否符合对应的规则
if (!isExp) {
// 可以弹出对应的提示信息
if (input === "") alert("请输入验证码");
else alert("验证码输入不正确");
// 结束验证的执行!
return;
}
// 如果符合正则的规则,倒计时60秒
let time = 10;
function setTime() {
// 将btn的按钮进行禁用
btn.disabled = true;
let n = setInterval(function() {
time--;
// console.log(time);
// 将time时间返给页面的中
btn.value = time + "s";
if (time == 0) {
// 将btn的按钮变为可用状态
btn.disabled = false;
// 将按钮的内容还原
btn.value = "发送";
clearInterval(n);
}
}, 1000);
}
// 最后调用这个函数
setTime();
}
</script>
</body>