One: Analyze the problem
- The problem statement is very clear, here is to implement an operation similar to remembering passwords in a form. Use localStorage to complete the operation. The final effect is that when the password is remembered, the page is refreshed and the information is displayed directly in the form.
Two: Solve the problem
- Build HTML form code structure
- Write js files that implement specific functions
- Use the related property method of localStorage to complete the function
- Refresh the page to achieve the effect of remembering the password
Three: code implementation
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>记住密码</title>
<style>
* {
margin: 0;
padding: 0;
}
.body {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.center-input {
width: 300px;
height: 400px;
border: 1px solid;
border-radius: 5px;
box-shadow: 2px 1px 1px black;
display: flex;
justify-content: center;
align-items: center;
}
.check-input {
display: flex;
justify-content: center;
align-items: center;
}
.checkbox-input {
margin: 5px;
}
</style>
<script src="./rempwd.js"></script>
</head>
<body>
<div class="body">
<div class="center-input">
<div class="input-content">
<div class="username-input">
请输入用户名:<input class="username" type="text">
</div>
<div class="password-input">
请再输入密码:<input class="password" type="password">
</div>
<div class="check-input">
是否记住用户名密码:<input class="checkbox" type="checkbox">
</div>
</div>
</div>
</div>
</body>
</html>
js:
window.onload = function(){
var username = document.querySelector('.username');
var password = document.querySelector('.password');
var checkbox = document.querySelector('.checkbox');
checkbox.addEventListener('change',function(){
if(this.checked){
localStorage.setItem('username',username.value);
localStorage.setItem('password',password.value)
}else{
localStorage.removeItem('username')
localStorage.removeItem('password')
}
})
if(localStorage.getItem('username') && localStorage.getItem('password')){
username.value = localStorage.getItem('username')
password.value = localStorage.getItem('password')
checkbox.checked = true
}
}
Four: Effect display
When you click Remember Password, the form information will be stored in localstorage, and when you refresh the page, the original form information will be remembered and displayed.