<body>
用户名:<input type="text" /><br />
密码:<input type="password" /><br />
<input type="checkbox" />七天免登录<br />
<input type="button" value="登录" />
<script src="cookie.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/blueimp-md5/2.16.0/js/md5.js"></script>
<script>
let aInput = document.querySelectorAll("input");
aInput[3].onclick = function () {
if (aInput[2].checked) {
setCookie("username", aInput[0].value, 7);
setCookie("password", md5(aInput[1].value), 7);
} else {
removeCookie("username");
removeCookie("password");
}
};
if (getCookie("username")) {
aInput[0].value = getCookie("username");
aInput[1].value = getCookie("password");
aInput[2].checked = true;
}
</script>
</body>
cookie.js
function setCookie(name, val, n) {
let oDate = new Date();
oDate.setDate(oDate.getDate() + n);
document.cookie = name + "=" + escape(val) + ";expires=" + oDate;
}
function getCookie(name) {
let strCookie = document.cookie;
let arrCookie = strCookie.split("; ");
for (let i = 0; i < arrCookie.length; i++) {
let arr = arrCookie[i].split("=");
if (arr[0] == name) {
return unescape(arr[1]);
}
}
}
function removeCookie(name) {
setCookie(name, 1, -1);
}