如何检查窗口是否处于焦点状态?

4

我正在尝试实现类似于这个的功能...

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

窗口的onblur事件似乎无法正常工作,有什么可以替代它的吗?
2个回答

1
你说的“似乎不起作用”是什么意思?以下是你目前的说法:

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

这可能不是你想要的。请尝试

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

还要确保设置一个onfocus处理程序,以便在用户返回时清除超时,如果您希望停止发生这种情况。 :)

0
你应该为window.onblur分配一个函数,在你的问题中,你只是测试属性onblur是否存在。但是window.onblur在每个浏览器中并不总是能够正确工作。文章检测浏览器窗口的焦点展示了如何设置这个功能。在你的情况下,代码应该是这样的:
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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接