
求随机验证码,0-9数字组成,26位字母的大小写组成,可以刷新的验证码,如果输入错误则显示弹窗,验证码输入错误

关注引自免费微信小程序:皆我百晓生
为了实现这个需求,你需要编写一个HTML页面,并在其中嵌入JavaScript代码。下面是一个详细的步骤,以及完整的HTML和JavaScript代码。
首先,创建一个HTML文件(例如:index.html),并添加以下内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Captcha</title>
<style>
.captcha {
display: flex;
align-items: center;
justify-content: center;
background-color: #288BC4;
padding: 10px;
border-radius: 5px;
font-size: 30px;
color: blue;
transform: skewX(-10deg);
}
button {
margin-top: 10px;
}
</style>
</head>
<body>
<div id="captcha" class="captcha"></div>
<input type="text" id="inputCaptcha" placeholder="请输入验证码">
<button onclick="checkCaptcha()">提交</button>
<button onclick="generateNewCaptcha()">看不清换一张</button>
<script src="script.js"></script>
</body>
</html>
接下来,在同一个目录下创建一个名为script.js的JavaScript文件,然后添加以下代码:
function generateNewCaptcha() {
const captchaDiv = document.getElementById('captcha');
const captchaInput = document.getElementById('inputCaptcha');
// 生成新的验证码
const newCaptcha = generateRandomCaptcha(6);
// 更新验证码显示
captchaDiv.textContent = newCaptcha;
// 清空输入框
captchaInput.value = '';
}
function generateRandomCaptcha(length) {
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
let captcha = '';
for (let i = 0; i < length; i++) {
captcha += chars[Math.floor(Math.random() * chars.length)];
}
return captcha;
}
function checkCaptcha() {
const captchaDiv = document.getElementById('captcha');
const captchaInput = document.getElementById('inputCaptcha');
const userCaptcha = captchaInput.value;
if (userCaptcha === captchaDiv.textContent) {
alert('验证码正确!');
} else {
alert('验证码输入有误!');
generateNewCaptcha();
}
}
这段代码实现了以下功能:
generateNewCaptcha函数用于生成一个新的6位验证码,并更新显示在界面上。generateRandomCaptcha函数生成一个指定长度的随机验证码字符串,包括数字和大小写字母。checkCaptcha函数负责验证用户输入的验证码是否与当前显示的验证码匹配。如果不匹配,它会显示错误消息并生成新的验证码。将这两个文件放在同一目录下,然后打开index.html文件,你应该能看到预期的效果。每次点击“看不清换一张”按钮,都会生成新的验证码,而点击“提交”按钮会检查用户的输入是否正确。