2014-11-03 84 views
2

今天我偶然發現了一個奇怪的Internet Explorer怪癖。我調用元素的焦點函數,然後綁定事件偵聽器。在所有瀏覽器中,它都按時間順序執行,但在IE中卻沒有。addEventListener觸發焦點之前的Internet Explorer焦點?

我有這樣一段代碼:

var t = document.getElementById('focusable'); 
 
t.focus(); 
 
t.addEventListener('focus', function() { 
 
    alert('This should only happen after the second focus.'); 
 
});
<input id="focusable">

我的問題是:
爲什麼會出現這種情況?,我怎樣才能解決它沒有setTimeout(fn,0);黑客。

注:我使用IE11

回答

2

爲什麼會出現這種情況?

大概是因爲在JavaScript線程退回到瀏覽器之前,IE實際上並沒有給出元素焦點。

如何在沒有setTimeout(fn,0)的情況下解決這個問題;黑客攻擊。

使用setTimeout在這種情況下似乎是正確的事情,而不是黑客。但是,如果它不起作用。 :-)

我討厭這樣說,但它聽起來像是你可能需要一個標誌,並有意確保第一焦點觸發您的處理程序:

(function() { 
 
    var flag = false; 
 
    var t = document.getElementById('focusable'); 
 
    t.blur(); 
 
    t.addEventListener('focus', function() { 
 
    if (!flag) { 
 
     flag = true; 
 
    } else { 
 
     snippet.log('This should only happen after the second focus.'); 
 
    } 
 
    }, false); 
 
    t.focus(); 
 
})();
<!-- Temporary snippet object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 
 
<input id="focusable">

+0

謝謝您的答覆。我只是測試了setTimeout「解決方案」的一致性,但偶爾會失敗。我把setEventListener放在settimeout裏面。 – A1rPun 2014-11-03 09:06:17

+0

謝謝T.J.我也討厭它,但至少這是一致的;) – A1rPun 2014-11-03 09:20:22

+0

@ A1rPun:不用擔心。公平的警告:上述工作適用於IE11和Chrome,但Firefox拒絕給予重點關注。它執行't.focus();'行,但沒有給出字段焦點 - 即使我只將該位放在'setTimeout'中。 V.怪異的,我知道我已經把焦點集中在Firefox的領域之前...... – 2014-11-03 09:22:31