通过visibilitychange事件来判断页面可见性的状态,通过document.hidden来判断当前页面是否在浏览
// 各种浏览器兼容 var hidden, visibilityChange; if (typeof document.hidden !== "undefined") { hidden = "hidden"; visibilityChange = "visibilitychange"; } else if (typeof document.mozHidden !== "undefined") { hidden = "mozHidden"; visibilityChange = "mozvisibilitychange"; } else if (typeof document.msHidden !== "undefined") { hidden = "msHidden"; visibilityChange = "msvisibilitychange"; } else if (typeof document.webkitHidden !== "undefined") { hidden = "webkitHidden"; visibilityChange = "webkitvisibilitychange"; } // 添加监听器,在title里显示状态变化 document.addEventListener(visibilityChange, function() { if(document[hidden]){ // 用户没有浏览当前页面 }else{ // 用户正在浏览当前页面 } }, false);
或者
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);