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("激活状态!")
}