JavaScript登入記住密碼
阿新 • • 發佈:2018-12-16
程式碼如下
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>記住密碼</title> </head> <body> <form id="loginForm"> <input id="user" type="text" placeholder="使用者名稱"><br> <input id="pswd" type="password" placeholder="密碼"><br> <label><input id="remember" type="checkbox">記住密碼</label><br> <input type='submit' value="登入"> </form> <script> window.onload = function(){ var oForm = document.getElementById('loginForm'); var oUser = document.getElementById('user'); var oPswd = document.getElementById('pswd'); var oRemember = document.getElementById('remember'); //頁面初始化時,如果帳號密碼cookie存在則填充 if(getCookie('user') && getCookie('pswd')){ oUser.value = getCookie('user'); oPswd.value = getCookie('pswd'); oRemember.checked = true; } //複選框勾選狀態發生改變時,如果未勾選則清除cookie oRemember.onchange = function(){ if(!this.checked){ delCookie('user'); delCookie('pswd'); } }; //表單提交事件觸發時,如果複選框是勾選狀態則儲存cookie oForm.onsubmit = function(){ if(remember.checked){ setCookie('user',oUser.value,7); //儲存帳號到cookie,有效期7天 setCookie('pswd',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); }; </script> </body> </html>