js实现验证码倒计时
实现验证码倒计时功能
验证码倒计时功能通常用于防止用户频繁发送验证码请求。以下是使用JavaScript实现验证码倒计时的方法。
获取验证码按钮
在HTML中添加一个按钮用于触发验证码发送:
<button id="getCodeBtn">获取验证码</button>
倒计时逻辑实现
// 获取按钮元素
const getCodeBtn = document.getElementById('getCodeBtn');
// 倒计时函数
function startCountdown(seconds) {
let remaining = seconds;
// 禁用按钮
getCodeBtn.disabled = true;
getCodeBtn.textContent = `${remaining}秒后重新获取`;
// 设置定时器
const timer = setInterval(() => {
remaining--;
if (remaining <= 0) {
// 倒计时结束
clearInterval(timer);
getCodeBtn.disabled = false;
getCodeBtn.textContent = '获取验证码';
} else {
// 更新按钮文字
getCodeBtn.textContent = `${remaining}秒后重新获取`;
}
}, 1000);
}
// 绑定点击事件
getCodeBtn.addEventListener('click', () => {
// 这里应该添加发送验证码的逻辑
// 发送成功后开始倒计时
startCountdown(60); // 60秒倒计时
});
样式优化
可以为禁用状态的按钮添加CSS样式,提升用户体验:
#getCodeBtn:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
完整示例
<!DOCTYPE html>
<html>
<head>
<style>
#getCodeBtn {
padding: 10px 15px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
#getCodeBtn:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
</style>
</head>
<body>
<button id="getCodeBtn">获取验证码</button>
<script>
const getCodeBtn = document.getElementById('getCodeBtn');
function startCountdown(seconds) {
let remaining = seconds;
getCodeBtn.disabled = true;
getCodeBtn.textContent = `${remaining}秒后重新获取`;
const timer = setInterval(() => {
remaining--;
if (remaining <= 0) {
clearInterval(timer);
getCodeBtn.disabled = false;
getCodeBtn.textContent = '获取验证码';
} else {
getCodeBtn.textContent = `${remaining}秒后重新获取`;
}
}, 1000);
}
getCodeBtn.addEventListener('click', () => {
// 这里添加发送验证码的AJAX请求
console.log('验证码已发送');
startCountdown(60);
});
</script>
</body>
</html>
注意事项
- 实际应用中应该在发送验证码请求成功后再启动倒计时
- 可以添加防止重复点击的逻辑
- 考虑页面刷新时保持倒计时状态(需要使用localStorage)
- 移动端适配时可能需要调整按钮样式和大小







