2010-07-05 145 views
4

我试图做一些类似的...如何检查窗口是否有焦点?

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

的window.onblur似乎并没有被工作,虽然是有什么我可以替换成?

回答

0

您应该为window.onblur指定一个函数,在您的问题中,您只测试属性onblur是否存在。但window.onblur并不总是在每个浏览器中正常工作。文章Detecting focus of a browser window显示了如何设置。在你的情况下,它会是这样的:

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

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

if (/*@[email protected]*/false) { // check for Internet Explorer 
    document.onfocusin = DTitFocus; 
    document.onfocusout = DTitBlur; 
} else { 
    window.onfocus = DTitFocus; 
    window.onblur = DTitBlur; 
} 
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处理程序以清除超时,如果您希望它在用户返回时停止发生。 :)