当用户在特定浏览器中进行选项卡切换以及用户进行应用程序切换时(从浏览器中退出),我需要了解该选项卡的可见性状态

var visibilityState,
    activeTab = (function(){
        var stateKey, eventKey, keys = {
            hidden: "visibilitychange",
            webkitHidden: "webkitvisibilitychange",
            mozHidden: "mozvisibilitychange",
            msHidden: "msvisibilitychange"
        };
        for (stateKey in keys) {
            if (stateKey in document) {
                eventKey = keys[stateKey];
                break;
            }
        }
        return function(c) {
            if (c) document.addEventListener(eventKey, c);
            return !document[stateKey];
        }
    })();
activeTab(function() {
    visibilityState = activeTab();
});

用途
$(window).blur(function(){
    if(!visibilityState){
        console.log("Tab Switch happened ...");
    }
});

最佳答案

您的目标浏览器支持什么?您是否尝试过研究Page Visibility API?或者,如果您使用的是jQuery,则可以像本answer中所示的那样执行$(window).on("blur focus", someCallbackHere)

09-25 19:47