很多登錄功能上都有個“記住密碼”的功能,其實無非就是對cookie的讀取。
引用
參照簡書 - 純JS操作Cookie
- 添加Cookie
setCookie ( name, value, expdays )
- 獲取Cookie
getCookie ( name )
- 刪除Cookie
delCookie ( name )
代碼說明
form表單
<!-- 登陸表單 -->
<form method="post" autocomplete="off" onsubmit="return check()">
<!-- 用戶名輸入 -->
<input type="text" name="username" id="username" required="required" >
<!-- 密碼輸入,禁用自動填充 -->
<input type="password" autocomplete="new-password" name="password" id="password" required="required">
<!-- 是否記住密碼復選框 -->
<input type="checkbox" id="isRmbPwd" name="isRmbPwd" checked="checked">記住密碼
<!-- 提交按鈕 -->
<input type="submit" value="提交">
</form>
提交檢查函數
點擊submit按鈕時,會調用此函數
function check ()
{
//獲取表單輸入:用戶名,密碼,是否保存密碼
var username = document.getElementById("username").value.trim() ;
var password = document.getElementById("password").value.trim() ;
var isRmbPwd = document.getElementById("isRmbPwd").checked ;
//判斷用戶名,密碼是否為空(全空格也算空)
if ( username.length != 0 && password.length != 0 )
{
//若復選框勾選,則添加Cookie,記錄密碼
if ( isRmbPwd == true )
{
setCookie ( "This is username", username, 7 ) ;
setCookie ( username, password, 7 ) ;
}
//否則清除Cookie
else
{
delCookie ( "This is username" ) ;
delCookie ( username ) ;
}
return true ;
}
//非法輸入提示
else
{
alert('請輸入必填字段!!!')
return false ;
}
}
文檔初始化函數
文檔加載完畢后,執行此函數
//將function函數賦值給onload對象
window.onload = function ()
{
//從Cookie獲取到用戶名
var username = getCookie("This is username") ;
//如果用戶名為空,則給表單元素賦空值
if ( username == "" )
{
document.getElementById("username").value="" ;
document.getElementById("password").value="" ;
document.getElementById("isRmbPwd").checked=false ;
}
//獲取對應的密碼,并把用戶名,密碼賦值給表單
else
{
var password = getCookie(username) ;
document.getElementById("username").value = username ;
document.getElementById("password").value = password ;
document.getElementById("isRmbPwd").checked = true ;
}
}
運行效果
初始狀態
初始表單.png
**說明 : **初始時,瀏覽器未保存Cookie,JS給各個表單賦空值,賦復選框未勾選狀態
鍵入用戶名密碼,未勾選復選框
表單鍵入,未勾選.png
提交,返回到表單頁面
回到表單頁面.png
**說明 : **未勾選保存密碼復選框,JS只提交表單到指定Action,未保存Cookie,同上
鍵入用戶名密碼,未勾選復選框
鍵入表單,勾選.png
提交表單,返回
記住了賬號密碼.png
**說明 : **瀏覽器成功保存了用戶名與密碼
此時再去掉復選框勾選狀態,提交
去掉復選框勾選.png
此時,瀏覽器就不再保存Cookie了
最終結果.png