JavaScript/jQuery: 测试窗口是否有焦点

如何测试浏览器是否有焦点?

94621 次浏览

我还没有在其他浏览器中测试过这个,但它似乎在 Webkit 中可以工作

尝试一下: < a href = “ http://jsfiddle.net/sckbk/”rel = “ norefrer”> http://jsfiddle.net/sckbk/

单击以启动间隔后,更改浏览器窗口的焦点以查看结果的更改。同样,只在 Webkit 中测试。

var window_focus;


$(window).focus(function() {
window_focus = true;
}).blur(function() {
window_focus = false;
});


$(document).one('click', function() {
setInterval(function() {
$('body').append('has focus? ' + window_focus + '<br>');
}, 1000);
});​

使用文档的 hasFocus 方法。 你可以在这里找到详细的描述和例子: HasFocus 方法

编辑: 添加小提琴 Http://jsfiddle.net/msjyv/3/

超文本标示语言

Currently <b id="status">without</b> focus...

JS

function check()
{
if(document.hasFocus() == lastFocusStatus) return;


lastFocusStatus = !lastFocusStatus;
statusEl.innerText = lastFocusStatus ? 'with' : 'without';
}


window.statusEl = document.getElementById('status');
window.lastFocusStatus = document.hasFocus();


check();
setInterval(check, 200);

HTML:

<button id="clear">clear log</button>
<div id="event"></div>​

Javascript:

$(function(){


$hasFocus = false;


$('#clear').bind('click', function() { $('#event').empty(); });


$(window)
.bind('focus', function(ev){
$hasFocus = true;
$('#event').append('<div>'+(new Date()).getTime()+' focus</div>');
})
.bind('blur', function(ev){
$hasFocus = false;
$('#event').append('<div>'+(new Date()).getTime()+' blur</div>');
})
.trigger('focus');


setInterval(function() {
$('#event').append('<div>'+(new Date()).getTime()+' has focus '+($hasFocus ? 'yes' : 'no')+'</div>');
}, 1000);
});​

测试

更新:

我会修复它,但 IE 不工作得很好

测试更新

简单的 javascript 代码片段

基于事件的:

function focuschange(fclass) {
var elems=['textOut','textFocus'];
for (var i=0;i<elems.length;i++) {
document.getElementById(elems[i]).
setAttribute('class',fclass);
}
}
window.addEventListener("blur",function(){focuschange('havnt')});
window.addEventListener("focus",function(){focuschange('have')});
focuschange('havnt');
.have                { background:#CFC; }
#textOut.have:after  { content:'';      }
.havnt               { background:#FCC; }
#textOut.havnt:after { content:' not';  }
<span id='textOut'>Have</span><span id='textFocus'> focus</span>

Interval pool based:

setInterval(function() {
var fclass='havnt';
if (document.hasFocus()) {
fclass='have';
};
var elems=['textOut','textFocus'];
for (var i=0;i<elems.length;i++) {
document.getElementById(elems[i]).
setAttribute('class',fclass);
}
},100);
#textOut.have:after  { content:'';     }
#textOut.havnt:after { content:' not'; }
.have  { background:#CFC; }
.havnt { background:#FCC; }
<span id='textOut'>Have</span><span id='textFocus'> focus</span>