在JavaScript中实现表单动态验证码通常涉及以下几个基础概念:
以下是一个简单的文本验证码实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Captcha</title>
</head>
<body>
<form id="captchaForm">
<label for="captcha">验证码:</label>
<input type="text" id="captcha" name="captcha" required>
<span id="captchaText"></span>
<button type="button" onclick="generateCaptcha()">刷新验证码</button>
<br><br>
<button type="submit">提交</button>
</form>
<script src="captcha.js"></script>
</body>
</html>
function generateCaptcha() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let captcha = '';
for (let i = 0; i < 6; i++) {
captcha += chars.charAt(Math.floor(Math.random() * chars.length));
}
document.getElementById('captchaText').innerText = captcha;
}
document.getElementById('captchaForm').addEventListener('submit', function(event) {
const userInput = document.getElementById('captcha').value;
const captchaText = document.getElementById('captchaText').innerText;
if (userInput !== captchaText) {
alert('验证码错误,请重试!');
event.preventDefault();
}
});
// 初始化验证码
generateCaptcha();
通过以上方法,可以实现一个基本的动态验证码系统,并根据需要进行扩展和优化。
领取专属 10元无门槛券
手把手带您无忧上云