自從最初撰寫此答案以來,由于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
。