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

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



牧羊人nacy
浏览 571回答 3
3回答

跃然一笑

HTML:<button id="clear">clear log</button><div id="event"></div>使用Javascript:$(function(){&nbsp; &nbsp; $hasFocus = false;&nbsp; &nbsp; $('#clear').bind('click', function() { $('#event').empty(); });&nbsp; &nbsp; $(window)&nbsp; &nbsp; &nbsp; &nbsp; .bind('focus', function(ev){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $hasFocus = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#event').append('<div>'+(new Date()).getTime()+' focus</div>');&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; .bind('blur', function(ev){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $hasFocus = false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#event').append('<div>'+(new Date()).getTime()+' blur</div>');&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; .trigger('focus');&nbsp; &nbsp; setInterval(function() {&nbsp; &nbsp; &nbsp; &nbsp; $('#event').append('<div>'+(new Date()).getTime()+' has focus '+($hasFocus ? 'yes' : 'no')+'</div>');&nbsp; &nbsp; }, 1000);});
打开App,查看更多内容
随时随地看视频慕课网APP