1. 程式人生 > >頁面不可見時觸發事件

頁面不可見時觸發事件

應用場景:頁面進入後臺時暫停背景音樂,再次進入時重新播放

load()方法可以加在body onload事件中,也可以等頁面載入完成後執行

var hidden, visibilityChange;

function load()
{
    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"; } document.addEventListener(visibilityChange, function () { console.log("當前頁面是否被隱藏:" + document[hidden]); if (document[hidden]) $("#_wxbgm")[0].pause(); else $("#_wxbgm")[0].play(); }, false); }