[英]How to detect when a tab is focused or not in Chrome with Javascript?
[英]How to know if a browser tab focused when it's loaded with Javascript?
還有一個類似的問題在這里 。 但是在最初加載頁面時它不起作用,因為如果例如用戶在新選項卡中打開頁面並且它沒有獲得焦點,則模糊事件將不會觸發。
那么最好的方法是什么呢?
目前,我的臨時解決方案是假設選項卡在加載時模糊,並將函數綁定到文檔的鼠標懸停事件,將其設置為焦點。 但是,如果用戶沒有在頁面上放置鼠標,那將無效。
借用您鏈接的代碼,將默認值設置為模糊:
<div id="blurDiv"></div>
<script>
var updateStatus = (function() {
// Private stuff
var el = document.getElementById('blurDiv');
// The updateStatus function
return function (evt) {
evt = evt || window.event;
var evtType = evt.type;
var state;
// Determine state
if (evtType == 'load' || evtType == 'blur' || evtType == 'focusout' ) {
state = 'blurred';
} else {
state = 'focussed';
}
// Now do something...
el.innerHTML += '<br>' + state
};
})();
window.onload = updateStatus;
if (/*@cc_on!@*/false) { // check for Internet Explorer
document.onfocusin = updateStatus;
document.onfocusout = updateStatus;
} else {
window.onfocus = updateStatus;
window.onblur = updateStatus;
}
</script>
IE似乎會引發很多額外的事件,每當有東西聚焦時,首先會出現模糊然后焦點,因此點擊頁面中的內容會產生大量的虛假模糊/焦點對。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.