Javascript chrome的document.hasFocus()
有人知道在Chrome上用什么代替hasFocus()吗?我想知道我的Chrome标签何时有焦点,这样我就可以在标题中闪烁一条警告信息Javascript chrome的document.hasFocus(),javascript,html,google-chrome,Javascript,Html,Google Chrome,有人知道在Chrome上用什么代替hasFocus()吗?我想知道我的Chrome标签何时有焦点,这样我就可以在标题中闪烁一条警告信息 干杯您可以使用document.activeElement标记。您可以通过这种方式监听onfocus/onblur事件并跟踪页面状态 <!DOCTYPE html> <html> <head> </head> <body> <div id="output"> &l
干杯您可以使用
document.activeElement
标记。您可以通过这种方式监听onfocus/onblur事件并跟踪页面状态
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="output">
</div>
<script>
var has_focus = true;
function print(str) {
var out = document.getElementById('output')
out.innerText = out.innerText + "\n" + str;
};
window.onfocus = function() {
print('focus');
has_focus = true;
};
window.onblur = function() {
print('blur');
has_focus = false;
};
</script>
</body>
</html>
var的焦点为true;
功能打印(str){
var out=document.getElementById('output')
out.innerText=out.innerText+“\n”+str;
};
window.onfocus=函数(){
打印(“焦点”);
has_focus=true;
};
window.onblur=函数(){
打印(“模糊”);
has_focus=false;
};
页面可见性API应该实现以下功能:
文档。隐藏
如果页面处于被视为可用的状态,则返回true
对用户隐藏,否则为false
当然,由于这是一个新的API,您需要使用不同的浏览器前缀:
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
} else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
}
var isHidden = document[hidden];
// or even
var isFocused = !isHidden;
请注意,您将推断页面在加载时具有焦点,但情况可能并不总是如此。自提出此问题以来,Chrome已经添加了对document.hasFocus()的支持。尽管现在他们有
document.hasFocus()
,但它实际上在不应该返回的情况下返回true
。谢谢,这真的帮了我的忙。