localstorage实现缓存用户名,有时间限制

2019-06-07  本文已影响0人  zsyyyyy
<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>

    <body>
        <div class="web">
            <ul class="login">
                <li>
                    <span>用户名:</span>
                    <input type="text" />
                </li>
                <li>
                    <span>密码:</span>
                    <input type="password" />
                </li>
                <li>
                    <label>
                            <input type="checkbox" class="remember" />
                            <span class="rPw">记住密码</span>
                    </label>
                    <button class="loginBtn">登录</button>
                </li>
            </ul>
        </div>
        <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
        <script type="text/javascript">
            let loginBtn = $(".loginBtn");
            let ipt = $(".login input");
            loginBtn.on("click", () => {
                     //prop设置或者获取选中对象的属性
                             //原生获取属性 .getAttribute("属性")
                if($(".remember").prop("checked")) {
                    var curTime = new Date().getTime();
                    localStorage.setItem("user", JSON.stringify({
                        user: ipt[0].value,
                        time: curTime
                    }));
                }
            })
            //转为对象
            var obj = JSON.parse(localStorage.getItem("user"));
            console.log(obj)
            if(typeof obj != "undefined"){      
                if(obj != null){                    
                    ipt[0].value = obj.user;
                    //封装到时间清除用户名
                    function cleartime(exp) {
                        var curTime2 = new Date().getTime(); //加载当前时间
                        if(curTime2 - obj.time > exp) {
                            localStorage.clear();//超时就清除掉
                        } else {
                            ipt[0].value = obj.user;
                        }
                    }
                    window.onload = () => {
                        cleartime(100000);
                    }
                }
            }
            
        </script>
    </body>
</html>
上一篇下一篇

猜你喜欢

热点阅读