<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录页面</title>
<link rel="stylesheet" href="./css/denglu.css">
</head>
<body>
<div class="login-container">
<h2>登录</h2>
<form id="loginForm">
<div class="form-group">
<label for="username">用户名:</label>
<input type="text" id="username" placeholder="用户名" required>
</div>
<div class="form-group">
<label for="password">密码:</label>
<input type="password" id="password" placeholder="密码" required>
</div>
<div class="captcha-container">
<img src="" alt="验证码" id="captchaImage" class="captcha-image">
<input type="text" id="captchaInput" placeholder="输入验证码" required>
</div>
<div class="form-group">
<button type="submit">登录</button>
</div>
</form>
</div>
<script>
// ...之前的验证码生成和显示逻辑...
function generateCaptcha() {
var canvas = document.createElement('canvas');
canvas.width = 100;
canvas.height = 30;
var ctx = canvas.getContext('2d');
ctx.font = '20px Arial';
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var captcha = '';
for (var i = 0; i < 4; i++) {
captcha += chars.charAt(Math.floor(Math.random() * chars.length));
}
ctx.fillText(captcha, 10, 25);
return { captcha: captcha, canvas: canvas };
}
// 显示验证码
function displayCaptcha() {
var captchaData = generateCaptcha();
var captchaImage = document.getElementById('captchaImage');
captchaImage.src = captchaData.canvas.toDataURL();
captchaImage.captcha = captchaData.captcha; // 将验证码文本存储在图片元素上
// 设置验证码10秒后失效
setTimeout(function () {
captchaImage.src = '';
captchaImage.captcha = '';
}, 100000);
}
// 绑定验证码图片点击事件
document.getElementById('captchaImage').addEventListener('click', function () {
displayCaptcha();
});
// 初始化验证码
displayCaptcha();
// 加载用户数据
function loadUsers(callback) {
fetch('users.json')
.then(response => response.json())
.then(data => callback(data))
.catch(error => console.error('加载用户数据失败:', error));
}
// 登录表单提交事件
document.getElementById('loginForm').addEventListener('submit', function (event) {
event.preventDefault();
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
var inputCaptcha = document.getElementById('captchaInput').value;
var actualCaptcha = document.getElementById('captchaImage').captcha;
// 验证验证码
if (inputCaptcha === actualCaptcha) {
// 验证码正确,加载用户数据进行验证
loadUsers(function (users) {
var user = users.find(u => u.username === username && u.password === password);
if (user) {
// 用户名和密码正确
location.href = 'https://www.baidu.com/'
} else {
// 用户名或密码错误
alert('用户名或密码错误!');
}
});
} else {
// 验证码错误
alert('验证码错误!');
displayCaptcha(); // 重新生成验证码
}
});
// 初始化验证码
displayCaptcha();
</script>
</body>
</html>
求助,为啥这个在vscode里live server可以正常跳转,但是从文件夹直接打开就不行呢?
文件是这么放的
|