用js和css代码实现上述登录页面
时间: 2024-02-26 19:56:45 浏览: 14
好的,以下是使用JS和CSS代码实现的登录页面示例:
HTML代码:
```html
<div class="login-page">
<form class="login-form">
<input type="text" id="username" placeholder="用户名">
<input type="password" id="password" placeholder="密码">
<button id="login-btn">登录</button>
</form>
<p id="error-msg" class="error-msg"></p>
</div>
```
CSS代码:
```css
.login-page {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
}
.login-form {
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
input {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: none;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
button {
padding: 10px;
border: none;
border-radius: 5px;
background-color: #007bff;
color: #fff;
cursor: pointer;
}
button:hover {
background-color: #0069d9;
}
.error-msg {
color: #f00;
}
```
JavaScript代码:
```javascript
const form = document.querySelector('.login-form');
const usernameInput = document.querySelector('#username');
const passwordInput = document.querySelector('#password');
const loginBtn = document.querySelector('#login-btn');
const errorMsg = document.querySelector('#error-msg');
form.addEventListener('submit', (event) => {
event.preventDefault();
const username = usernameInput.value;
const password = passwordInput.value;
if (username === 'admin' && password === '123456') {
// 登录成功
errorMsg.textContent = '';
window.location.href = '/home.html'; // 跳转到主页面
} else {
// 登录失败
errorMsg.textContent = '用户名或密码错误!';
}
});
usernameInput.addEventListener('input', () => {
errorMsg.textContent = '';
});
passwordInput.addEventListener('input', () => {
errorMsg.textContent = '';
});
```
说明:
- HTML代码中使用了一个`<p>`标签用于显示错误信息,初始内容为空。
- JavaScript代码中,获取了表单元素、用户名输入框、密码输入框、登录按钮和错误信息标签等元素,并添加了登录表单的提交事件,用于检查用户名和密码是否正确。如果用户名和密码正确,则跳转到主页面;否则,显示错误信息。
- 在用户名和密码输入框中添加了`input`事件,用于在用户输入时清空错误信息。
希望这个示例对您有所帮助!