以下是一个简单的JavaScript登录页面代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录页面</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.login-container {
border: 1px solid #ccc;
padding: 20px;
width: 300px;
text-align: center;
}
input[type="text"], input[type="password"] {
width: calc(100% - 22px);
padding: 10px;
margin-bottom: 10px;
}
button {
width: 100%;
padding: 10px;
background-color: #007BFF;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div class="login-container">
<h2>登录</h2>
<form id="loginForm">
<input type="text" id="username" placeholder="用户名" required>
<input type="password" id="password" placeholder="密码" required>
<button type="submit">登录</button>
</form>
</div>
<script>
document.getElementById('loginForm').addEventListener('submit', function(event) {
event.preventDefault(); // 阻止表单默认提交行为
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
// 这里可以添加与服务器验证的逻辑
if(username === 'admin' && password === '123456') {
alert('登录成功!');
// 可以跳转到其他页面
} else {
alert('用户名或密码错误!');
}
});
</script>
</body>
</html>这个代码实现了一个简单的登录页面,使用了HTML来构建页面结构,CSS进行样式设计,JavaScript处理表单提交事件和简单的用户验证逻辑。
这是一个基于浏览器的客户端验证示例。在实际应用中,通常还需要服务器端验证以确保安全性。
适用于学习目的、小型项目或者作为更复杂登录系统的简化版本。
对于安全性问题,可以在服务器端使用Node.js和Express框架进行验证:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/login', (req, res) => {
const { username, password } = req.body;
if(username === 'admin' && password === '123456') {
res.status(200).send('登录成功!');
} else {
res.status(401).send('用户名或密码错误!');
}
});
app.listen(3000, () => console.log('服务器运行在 http://localhost:3000'));这样,即使客户端的JavaScript被禁用或修改,服务器端的验证仍然可以保证系统的安全性。