js 如何实现登录时记住密码
一般的网页版网站登录的时候都会有记住密码的功能,需求是勾选记住密码,下次登录会自动带出来用户名和密码。
直接上代码
JS 代码如下:
window.onload = function(){
var oForm = document.getElementById('signupForm');
var oUser = document.getElementById('username');
var oPswd = document.getElementById('password');
var oRemember = document.getElementById('rememberme');
//页面初始化时,如果帐号密码cookie存在则填充
if (getCookie('username') && getCookie('password')) {
oUser.value = getCookie('username');
oPswd.value = getCookie('password');
oRemember.checked = true;
}
//复选框勾选状态发生改变时,如果未勾选则清除cookie
oRemember.onchange = function() {
if (!this.checked) {
delCookie('username');
delCookie('password');
}
};
//表单提交事件触发时,如果复选框是勾选状态则保存cookie
oForm.onsubmit = function() {
if (oRemember.checked) {
setCookie('username', oUser.value, 7); //保存帐号到cookie,有效期7天
setCookie('password', oPswd.value, 7); //保存密码到cookie,有效期7天
}
};
};
//设置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);
if (arr) {
return arr[1];
} else {
return '';
}
};
//删除cookie
function delCookie(name) {
setCookie(name, null, -1);
};
HTML 代码如下:
<form id="signupForm" autocomplete="off">
<h2 class="no-margins text-center">无人机巡检系统</h2>
<input type="text" id="username" name="username" class="form-control uname" placeholder="用户名" />
<input type="password" id="password" name="password" class="form-control pword" placeholder="密码" />
<div class="row m-t" th:if="${captchaEnabled==true}">
<div class="col-xs-6">
<input type="text" name="validateCode" class="form-control code" placeholder="验证码" maxlength="5" />
</div>
<div class="col-xs-6">
<a href="javascript:void(0);" title="点击更换验证码">
<img th:src="@{captcha/captchaImage(type=${captchaType})}" class="imgcode" width="85%"/>
</a>
</div>
</div>
<div class="checkbox-custom" th:classappend="${captchaEnabled==false} ? 'm-t'">
<input type="checkbox" id="rememberme" name="rememberme"> <label for="rememberme">记住我</label>
</div>
<button class="btn btn-success btn-block" id="btnSubmit" data-loading="正在验证登录,请稍后...">登录</button>
</form>
cookie 效果如下: