你如何测试浏览器是否有焦点?
JavaScript / jQuery:测试窗口是否有焦点
IT技术
javascript
jquery
events
2021-01-25 23:12:04
4个回答
使用文档的 hasFocus 方法。您可以在此处找到详细说明和示例: hasFocus 方法
编辑:添加小提琴 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);
我没有在其他浏览器中测试过这个,但它似乎在 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);
});
简单的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>
基于间隔池:
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>
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 不能很好地工作
其它你可能感兴趣的问题