首先先引入Base64.js文件
https://cdn.jsdelivr.net/npm/js-base64@3.7.2/base64.min.js
base64对于空格等特殊符号的加解码更加完善,不会像原生js中的加解码会在解码时出现一些小问题。
/**
* 登录状态
*/
function loginStatus() {
const checkbox = document.querySelector('.check input');
const password = document.querySelector('#password');
const phone = document.querySelector('#phone');
phone.oninput = function() {
localStorage.setItem('phone', JSON.stringify(phone.value));
};
password.oninput = function() {
localStorage.setItem('tokens', Base64.encode(password.value.split(',').reverse().join(',')));
};
checkbox.onclick = function() {
localStorage.setItem('checked', JSON.stringify(checkbox.checked));
if (checkbox.checked == false) {
localStorage.password = '';
localStorage.phone = '';
}
};
if (localStorage.checked) checkbox.checked = JSON.parse(localStorage.checked);
if (checkbox.checked) {
if (localStorage.tokens) password.value = Base64.decode(localStorage.tokens.split(',').reverse().join(','));
if (localStorage.phone) phone.value = JSON.parse(localStorage.phone);
}
}