2010-08-13 52 views
74

如何測試瀏覽器是否有焦點?JavaScript/jQuery:測試窗口是否有焦點

+0

另請參閱http://stackoverflow.com/questions/483741/how-to-determine-which-html-page-element-has-focus它也可以回答這個問題。 – 2011-06-29 15:12:23

+15

嘗試'document.hasFocus()',它返回一個布爾值。 它被構建到規範中,所以它可以在沒有jQuery的情況下完成。 – 2013-02-04 21:41:42

回答

74

我沒有在其他瀏覽器中測試過,但它似乎在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); 
});​ 
+0

@jball - 必須是IE?在Webkit和Firefox中,窗口的任何激活都會觸發焦點。我想知道是否有一個IE的解決方法。另外,你在你的網頁上測試過嗎?也許有問題,因爲jsFiddle使用框架? – user113716 2010-08-13 19:39:32

+0

此外,按Tab鍵似乎永久打破它。實際上Chrome實際上是 – jball 2010-08-13 19:39:44

+0

。經過進一步測試,我的第一個評論可能是錯誤的 - 突破它的標籤鍵似乎更一致。 – jball 2010-08-13 19:40:59

155

使用文件的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); 
+3

我嘗試了上述鏈接的示例,它在IE7 +,Chrome和FF4中運行良好。爲你+1。 – 2011-05-03 14:56:57

+1

很棒的小功能,比我碰到的其他jQuery等價物的效果要好得多。 – Heath 2011-08-31 20:10:24

+3

比接受的答案更有用,當窗口沒有對焦時,我遇到了加載計時器的問題。 – Kokos 2011-10-17 14:06:28

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); 
});​ 

test

UPDATE:

我會解決它,但IE瀏覽器不能很好地工作

test update

+0

在我的測試中不一致地在IE8中工作。 – 2010-08-27 15:22:57

+0

切換標籤時,顯然模糊不會觸發。 :( – 2013-11-12 20:41:58