Hohohoho, follow up from the previous article using localStorage to complete the function of remembering passwords
One: Analyze the problem
- Here you need to use document.cookie to realize the function
Two: Solve the problem
- It is also the html code structure of my last article
- js to achieve specific functions
- To define a method to get a cookie, a method to set a cookie and a method to delete a cookie. The function of refreshing and remembering the password is realized by calling the method.
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){
setCookie('username',username.value,5)
setCookie('password',password.value,5)
}else{
delCookie('username')
delCookie('password')
}
})
if(getCookie('username')&& getCookie('password')){
username.value = getCookie('username')
password.value = getCookie('username')
checkbox.checked = true
}
//设置cookie
function setCookie(name,value,day){
var date = new Date();
date.setDate(date.getDate() + day);
document.cookie = name + '=' + value + ';expires='+ date;
};
//获取cookie
function getCookie(name){
var reg = RegExp(name+'=([^;]+)');
var arr = document.cookie.match(reg);
// console.log(arr)
if(arr){
return arr[1];
}else{
return '';
}
};
//删除cookie
function delCookie(name){
setCookie(name,null,-1);
}
}
Four: Effect display