千万里不及你
自从最初撰写此答案以来,由于W3C ,新规范已达到推荐状态。在网页浏览权限API(在MDN)现在允许当一个页面被隐藏到用户我们更准确地检测。目前的浏览器支持Chrome 13+Internet Explorer 10+Firefox 10+Opera 12.10+ [ 阅读笔记 ]以下代码使用API,回退到不兼容的浏览器中不太可靠的模糊/焦点方法。(function() {
var hidden = "hidden";
// Standards:
if (hidden in document)
document.addEventListener("visibilitychange", onchange);
else if ((hidden = "mozHidden") in document)
document.addEventListener("mozvisibilitychange", onchange);
else if ((hidden = "webkitHidden") in document)
document.addEventListener("webkitvisibilitychange", onchange);
else if ((hidden = "msHidden") in document)
document.addEventListener("msvisibilitychange", onchange);
// IE 9 and lower:
else if ("onfocusin" in document)
document.onfocusin = document.onfocusout = onchange;
// All others:
else
window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onchange;
function onchange (evt) {
var v = "visible", h = "hidden",
evtMap = {
focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h };
evt = evt || window.event;
if (evt.type in evtMap)
document.body.className = evtMap[evt.type];
else
document.body.className = this[hidden] ? "hidden" : "visible";
}
// set the initial state (but only if browser supports the Page Visibility API)
if( document[hidden] !== undefined )
onchange({type: document[hidden] ? "blur" : "focus"});})();onfocusin并且onfocusout是IE 9及更低版本所必需的,而所有其他人都使用onfocus和onblur使用onpageshow和的iOS除外onpagehide。