如何测试浏览器是否具有焦点?
答案 0 :(得分:160)
使用文档的hasFocus方法。 您可以在此处找到详细说明和示例: hasFocus method
编辑:添加小提琴 http://jsfiddle.net/Msjyv/3/
HTML 的
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);
答案 1 :(得分:77)
我没有在其他浏览器中测试过这个,但它似乎在Webkit中有效。我会让你试试IE。 :O)
试一试: 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);
});
答案 2 :(得分:1)
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不能很好地工作
答案 3 :(得分:1)
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>
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>