开发者

How do I check if the window has focus?

I'm trying to do something similar to this...

if (window.onblur) {
    setTimeout(function开发者_StackOverflow () {
        DTitChange(name)
    }, 1000)
} else {
    document.title = dtit
}

The window.onblur doesn't seem to be working though, is there something I can replace that with?


What do you mean by doesn't seem to be working? Here's what you are currently saying:

If there's an onblur event handler:
    execute DTitChange once ever second.
Else 
    document.title = dtit

Which is probably not what you want. Try

window.onblur = function () {
    setTimeout(function () { DTitChange(name) }, 1000);
};

also make sure that you set an onfocus handler as to clear the timeout if you want it to stop happening when the user returns. :)


You should assign a function to window.onblur, in your question you're only testing if the property onblur exists. But window.onblur doesn't always work correctly in every browser. The article Detecting focus of a browser window shows how to set this up. In your case it would be something like:

function DTitBlur() {
    /* change title of page to ‘name’ */
    setTimeout(function () {
        DTitChange(name)
    }, 1000);
}

function DTitFocus() {
    /* set title of page to previous value */
}

if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.onfocusin = DTitFocus;
    document.onfocusout = DTitBlur;
} else {
    window.onfocus = DTitFocus;
    window.onblur = DTitBlur;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜