NatChen

Once you have chosen the road of life, you have to be brave enough to go to the end and never look back.

Page Visibility(网页可见性) API与登录同步引导页实例页面

页面1 

HTML代码:

<p id="loginInfo"></p>
JS代码:
(function() {
    if (typeof pageVisibility.hidden !== "undefined") {
        var eleLoginInfo = document.querySelector("#loginInfo");
        var funLoginInfo = function() {
            var username = localStorage.username || sessionStorage.username;
            if (username) {
                eleLoginInfo.innerHTML = '欢迎回来,<strong>' + username + '</strong>';
                sessionStorage.username = username;
            } else {
                eleLoginInfo.innerHTML = '您尚未登录,请<a target="_blank" href="'+ location.href.replace("-1.", "-2.") +'">登录</a>';
            }    
        }
        pageVisibility.visibilitychange(function() {
            if (!this.hidden) funLoginInfo();
        });
        
        funLoginInfo();
        
        // 页面关闭清除localStorage
        window.addEventListener("unload", function() {
            localStorage.removeItem("username");
        })
    } else {
        alert("弹框???没错,因为你的这个浏览器不支持Page Visibility API的啦!");    
    }
})();

 

页面2

HTML代码:
<form id="loginForm" action="" method="post">
    <p>用户名:<input type="text" name="username" required /></p>
    <p>密码:<input type="password" name="password" required /></p>
    <p><input type="submit" /></p>
</form>
JS代码:
(function() {
    if (typeof window.screenX === "number") {
    var eleLoginForm = document.querySelector("#loginForm");
        eleLoginForm.addEventListener("submit", function(e) {
            localStorage.username = document.querySelector("input[name='username']").value;
            alert("登录成功!现在可以回到刚才的页面了!");
            this.reset();
            e.preventDefault();
        }, false);
    } else {
        alert("弹框???没错,因为你的这个浏览器不支持HTML5表单的啦!");    
    }
})();

 

posted @ 2018-04-13 15:34  NatChen  阅读(278)  评论(0编辑  收藏  举报