写一段登录数字校验的前端代码
时间: 2024-04-22 15:22:43 浏览: 11
下面是一个简单的登录数字校验的前端代码示例:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login with Verification Code</title>
<style>
#code-box {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 20px;
}
#code-box input[type="text"] {
width: 50%;
padding: 10px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 5px;
outline: none;
}
#code-box button {
padding: 10px 20px;
font-size: 16px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Login with Verification Code</h1>
<form>
<div>
<label for="username">Username:</label>
<input type="text" name="username" id="username">
</div>
<div>
<label for="password">Password:</label>
<input type="password" name="password" id="password">
</div>
<div id="code-box">
<input type="text" name="code" id="code">
<button type="button" id="code-btn">Get Code</button>
</div>
<button type="submit">Login</button>
</form>
<script>
// 生成随机数字验证码
function generateCode() {
var code = "";
for (var i = 0; i < 6; i++) {
code += Math.floor(Math.random() * 10);
}
return code;
}
// 点击获取验证码按钮,生成验证码并显示在输入框中
document.getElementById("code-btn").addEventListener("click", function() {
var code = generateCode();
document.getElementById("code").value = code;
});
// 提交表单时,校验验证码
document.querySelector("form").addEventListener("submit", function(event) {
var inputCode = document.getElementById("code").value;
var generatedCode = generateCode();
if (inputCode !== generatedCode) {
alert("Verification code is incorrect!");
event.preventDefault(); // 阻止表单提交
}
});
</script>
</body>
</html>
```
在这个示例代码中,我们使用了HTML、CSS和JavaScript来实现登录数字校验的功能。具体来说,我们在表单中添加了一个验证码输入框和一个获取验证码的按钮,当用户点击获取验证码按钮时,会生成一个随机的6位数字验证码并显示在输入框中。当用户提交表单时,我们会比较用户输入的验证码和生成的验证码是否一致,如果不一致则阻止表单提交并弹出提示框。