laijbin / Blog

Note insights and personal development.
0 stars 0 forks source link

Page Visibility #10

Open laijbin opened 8 years ago

laijbin commented 8 years ago

判断当前页面实现

window.onload = 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";
        }
    }
};

在当前页面,但用户有一段时间不操作,如离开忙其他事情

var operationCount = 0;
window.onload=function(){
    document.body.onmousedown = document.body.onmouseover = document.body.onkeydown =function(){
        document.body.className = "visible";
        operationCount++;
        window.status=operationCount;
        // console.debug(operationCount);
    }
    setInterval("operationCountCheck()",10*1000);
};
function operationCountCheck(){
    if(operationCount == 0){
        document.body.className = "hidden";
    }else{
        operationCount = 0;
    }
}

拓展阅读:Page Visibility(页面可见性) API介绍、微拓展