js基础6 — 离开页面消息提示功能

<script type="text/javascript">
    "use strict";
    var console = window.console;
    var title = document.title;

    if (document.hasFocus()) {
        console.log('文档已获取焦点');
    } else {
        console.log('文档已失去焦点');
    }

    var title = document.title;
    var time = null;

    function showTitle() {
        if (document.title == title) {
            document.title = '你有新消息';
        } else {
            document.title = title;
        }
    }

    function myFunction() {
        if (document.hasFocus()) {
            document.body.innerHTML = "文档已获取焦点。";
            clearInterval(time);
            time = null;
            document.title = title;
        } else {
            document.body.innerHTML = "文档失去焦点。";
        }
    }
    
    document.addEventListener('visibilitychange', function () {
        // 页面不可见
        if (document.visibilityState === 'hidden') {
            time = setInterval(showTitle,500);
        }
        // 页面可见
        if (document.visibilityState === 'visible' ) {
            setInterval("myFunction()", 1);
        }
    });
</script>

 

posted @ 2019-03-24 18:12  PopeyeSailorMan  阅读(336)  评论(0编辑  收藏  举报