js如何判断当前页面是否处于激活状态

方式1:监听事件visibilitychange
具体实现方式如下:

var hiddenProperty = 'hidden' in document ? 'hidden' :    
    'webkitHidden' in document ? 'webkitHidden' :    
    'mozHidden' in document ? 'mozHidden' :  null;
var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');
var onVisibilityChange = function(){
    if (!document[hiddenProperty]) {    
        alert("未激活状态!");
    }else{
        alert("激活状态!")
    }
}
document.addEventListener(visibilityChangeEvent, onVisibilityChange);

方式2:监听事件blur和focus

window.onblur = function(e){
	console.log("未激活状态!")
}
window.onfocus = function(e){
	console.log("激活状态!")
}

你可能感兴趣的:(javascript)