在开发中,希望当前页面如果不是活动页面,即用户切换了tab页,或者用户把浏览器缩小隐藏了
这个时候,我们希望页面暂停,比如游戏暂停,视频停止播放等。
那怎么做呢?
1、使用document.hidden来判定是否隐藏
var hidden, state, visibilityChange;
if (typeof document.hidden !== "undefined") {
hidden = "hidden";
visibilityChange = "visibilitychange";
state = "visibilityState";
} else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden";
visibilityChange = "mozvisibilitychange";
state = "mozVisibilityState";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
state = "msVisibilityState";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
state = "webkitVisibilityState";
}
// 添加监听器,监听当前是否活动页面
document.addEventListener(visibilityChange, function() {
document.title = document[state];
}, false);
2、使用requestAnimationFrame,如果当前不是活动页面,则requestAnimationFrame不会回调。setInterval会一直走
setInterval(()=>{
console.log(111);
(window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame)(function(){
console.log(2);
});
})