用js写一个验证登录的页面
时间: 2024-05-06 11:15:24 浏览: 11
好的,以下是一个简单的验证登录的页面的代码示例:
HTML部分:
```html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Login</h1>
<form id="login-form">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<button type="submit">Login</button>
</form>
<script src="script.js"></script>
</body>
</html>
```
CSS部分:
```css
body {
background-color: #f2f2f2;
}
h1 {
text-align: center;
margin-top: 50px;
}
form {
background-color: #fff;
max-width: 500px;
margin: 50px auto;
padding: 20px;
box-shadow: 0px 0px 5px rgba(0,0,0,0.3);
}
label {
display: block;
margin-bottom: 5px;
}
input {
display: block;
width: 100%;
padding: 10px;
margin-bottom: 10px;
border-radius: 5px;
border: 1px solid #ccc;
font-size: 16px;
}
button {
display: block;
width: 100%;
padding: 10px;
margin-top: 10px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
button:hover {
background-color: #0062cc;
}
```
JS部分:
```js
const form = document.getElementById('login-form');
const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('password');
form.addEventListener('submit', function(event) {
event.preventDefault();
const usernameValue = usernameInput.value.trim();
const passwordValue = passwordInput.value.trim();
if (usernameValue === '') {
alert('Please enter your username');
return;
}
if (passwordValue === '') {
alert('Please enter your password');
return;
}
if (usernameValue === 'myusername' && passwordValue === 'mypassword') {
alert('Login successful!');
// redirect to home page or do something else here
} else {
alert('Invalid username or password');
}
});
```
这个页面会在用户点击登录按钮时,通过JS脚本对输入的用户名和密码进行验证,如果验证成功则弹出登录成功的提示框,否则弹出登录失败的提示框。