Page Visibility(网页可见性) API基本属性与事件实例页面

回到相关文章 »

代码:

HTML代码:
<div>页面载入时候:</div>
<div><code>pageVisibility.hidden: </code><span id="hidden"></span></div>
<div><code>pageVisibility.visibilityState: </code><span id="visibilityState"></span></div>
<p>记录页面状态的改变以及时间:</p>
<ul id="visibilitychange"></ul>
                
JS代码:
var pageVisibility = (function() {
    var prefixSupport, keyWithPrefix = function(prefix, key) {
        if (prefix !== "") {
            // 首字母大写
            return prefix + key.slice(0,1).toUpperCase() + key.slice(1);    
        }
        return key;
    };
    var isPageVisibilitySupport = (function() {
        var support = false;
        if (typeof window.screenX === "number") {
            ["webkit", "moz", "ms", "o", ""].forEach(function(prefix) {
                if (support == false && document[keyWithPrefix(prefix, "hidden")] != undefined) {
                    prefixSupport = prefix;
                    support = true;   
                }
            });        
        }
        return support;
    })();
    
    var isHidden = function() {
        if (isPageVisibilitySupport) {
            return document[keyWithPrefix(prefixSupport, "hidden")];
        }
        return undefined;
    };
    
    var visibilityState = function() {
        if (isPageVisibilitySupport) {
            return document[keyWithPrefix(prefixSupport, "visibilityState")];
        }
        return undefined;
    };
    
    return {
        hidden: isHidden(),
        visibilityState: visibilityState(),
        visibilitychange: function(fn, usecapture) {
            usecapture = undefined || false;
            if (isPageVisibilitySupport && typeof fn === "function") {
                return document.addEventListener(prefixSupport + "visibilitychange", function(evt) {
                    this.hidden = isHidden();
                    this.visibilityState = visibilityState();
                    fn.call(this, evt);
                }.bind(this), usecapture);
            }
            return undefined;
        }
    };    
})(undefined);
                

效果:

页面载入时候:
pageVisibility.hidden:
pageVisibility.visibilityState:

记录页面状态的改变以及时间: