首页 > 代码库 > TML5

TML5

1、document.hidden

  支持page visibility的浏览器在document上添加一个hidden属性(不同浏览器可能需要前缀,如webkitHidden),看当前tab页是否激活,激活(focus)时document.hidden属性是false,否则是true。

  document还会添加一个visibilityState属性,该属性有4个可能值,分别如下:

  hidden:当浏览器最小化、切换tab(the page is on a background tab)、电脑锁屏时visibilityState值是hidden

  visible:当浏览器顶级context(top level browsing context)的document至少显示在一个屏幕(screen)当中时,返回visible;当浏览器窗口没有最小化,但是浏览器被其他应用遮挡时,visibilityState值也是visible

  prerender:文档加载离屏(is loaded off-screen)或者不可见时返回prerender,浏览器可选择性的支持这个属性(not all browsers will necessarily support it)

  unloaded:当文档(document)将要被unload时返回unloaded,浏览器可选择性的支持这个属性

  此外就是事件支持,document上会添加visibilitychange事件,当UA的顶级document可见性(visibility)改变时触发

  兼容浏览器

 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"; } // Add a listener that constantly changes the title document.addEventListener(visibilityChange, function() { console.ifo(document.hidden); }, false);