lynxerzhang / JSSkills

MIT License
0 stars 0 forks source link

在js中如何进行标签页是否切换的判断? #2

Open lynxerzhang opened 6 years ago

lynxerzhang commented 6 years ago

visibilitychange 这个事件只能针对当前标签页是否失去焦点来进行判断,所以需要再加上判断document的hidden属性来做到对标签页是否切换的判断。

var tabPageVisibilityManager = (function(){
    var hiddenProperty = ["hidden", "webkitHidden", "mozHidden", "msHidden"];
    var len = hiddenProperty.length;
    var propertyKey = "";
    for(var i = 0; i < len; i ++){
        if(hiddenProperty[i] in document){
            propertyKey = hiddenProperty[i];
            break;
        }
    }
    var eventKey = "";
    if(propertyKey && propertyKey != ""){
        eventKey = propertyKey.replace(/hidden/i, "visibilitychange");
    }
    return function(pause_callback, resume_callback) {
        document.addEventListener(eventKey, function(){
            if(!document[propertyKey]){
                if(resume_callback != null){
                    resume_callback();
                }
            }else{
                if(pause_callback != null){
                    pause_callback();
                }
            }
        });
    }
})();

tabPageVisibilityManager(function(){
    console.log("pause");
}, function(){
    console.log("resume");
});