js 怎样判断用户是否在浏览当前页面?

可以通过document.hidden属性判断当前页面是否是激活状态。

兼容性:IE10+,Firefox10+,Chrome14+,Opera12.1+,Safari7.1+
兼容性写法示例:

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]) {    
        console.log('页面非激活');
    }else{
        console.log('页面激活')
    }
}
document.addEventListener(visibilityChangeEvent, onVisibilityChange);

你可能感兴趣的:(前端开发,#,JavaScript,晴天有点孤单)