页面不可见时触发事件

应用场景:页面进入后台时暂停背景音乐,再次进入时重新播放

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);
}

 

posted @ 2019-01-10 13:14  过一天日子修一天缘  阅读(804)  评论(0编辑  收藏  举报