验证码倒计时是一种常见的安全措施,用于防止用户频繁点击发送验证码按钮,从而减少恶意请求和提高系统的安全性。下面我将详细介绍如何使用JavaScript实现验证码倒计时功能。
验证码倒计时通常涉及以下几个概念:
setTimeout
或setInterval
函数用于设置定时任务。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>验证码倒计时</title>
</head>
<body>
<button id="sendCodeBtn">发送验证码</button>
<script src="countdown.js"></script>
</body>
</html>
document.addEventListener('DOMContentLoaded', function() {
const sendCodeBtn = document.getElementById('sendCodeBtn');
let countdown = 60; // 初始倒计时时间,单位秒
let timer = null;
function startCountdown() {
sendCodeBtn.disabled = true;
sendCodeBtn.textContent = `${countdown}秒后重试`;
timer = setInterval(() => {
countdown--;
sendCodeBtn.textContent = `${countdown}秒后重试`;
if (countdown <= 0) {
clearInterval(timer);
sendCodeBtn.disabled = false;
sendCodeBtn.textContent = '发送验证码';
countdown = 60; // 重置倒计时
}
}, 1000);
}
sendCodeBtn.addEventListener('click', startCountdown);
});
localStorage
或sessionStorage
保存倒计时状态,页面加载时恢复。通过上述方法,你可以实现一个简单且有效的验证码倒计时功能,提升系统的安全性和用户体验。