在user和pass中输入内容 点击保留登录 将他们保存在cookie中 关闭页面重新打开时 将用户名和密码自动输入这两个输入框 点击删除登录时 将输入框内容清空 并将cookie中的保留的用户名和密码删除
<!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>Document</title>
</head>
<body>
<input type="text" name="user"/>
<input type="password" name="pass">
<button>保留登录</button>
<button>删除登录</button>
<script>
// 在user和pass中输入内容 点击保留登录 将他们保存在cookie中 关闭页面重新打开时 将用户名和密码自动输入这两个输入框 点击删除登录时 将输入框内容清空 并将cookie中的保留的用户名和密码删除
var aIn = document.getElementsByTagName("input");
var aBtn = document.getElementsByTagName("button");
if(getCookie("user")&&getCookie("pass")){
aIn[0].value = getCookie("user");
aIn[1].value = getCookie("pass");
};
aBtn[0].onclick = function (){
setCookie("user",aIn[0].value,7);
setCookie("pass",aIn[1].value,7);
}
aBtn[1].onclick = function (){
removeCookie("user");
removeCookie("pass");
aIn[0].value = "";
aIn[1].value = "";
}
// 设置cookie
function setCookie(key,value,t){
var oDate = new Date();
oDate.setDate(oDate.getDate()+t);
document.cookie = key+'='+encodeURI(value)+';expires='+oDate.toGMTString();
}
// decodeURI(document.cookie);获取cookie
// 获取cookie
function getCookie(key){
var arr1 = document.cookie.split('; ');
for(var i=0;i<arr1.length;i++){
var arr2 = arr1[i].split('=');
if(arr2[0]==key){
return decodeURI(arr2[1]);
}
}
}
// 删除cookie
function removeCookie(key){
setCookie(key,'',-1);
// 设置和原来相同的key value 后设置的会覆盖先前的 所以将它变为空字符串 前一天过期
}
</script>
</body>
</html>