讀完element.focus()
method之後,我編寫了下面的代碼來模糊focus()
調用返回到事件循環之前由文檔聚焦的元素。
這個想法是我們爲每個元素添加一個焦點偵聽器,然後在onload之後刪除焦點偵聽器,以便在用戶事件(如jsfiddle.com或Google結果頁面)之後調用focus()
的網站仍然可以工作在頁面加載後正確。
警告:我一直無法弄清楚如何讓Chrome禁用autofocus
fields。
內容的腳本(稱之爲unfocus.js):
document.addEventListener('DOMNodeInsertedIntoDocument', onInsertedIntoDocument, true);
document.addEventListener('DOMNodeRemovedFromDocument', onRemovedFromDocument, true);
window.addEventListener('load', function(e) {
setTimeout(function() {
removeOnFocus(document.documentElement);
document.removeEventListener('DOMNodeInsertedIntoDocument', onInsertedIntoDocument, true);
document.removeEventListener('DOMNodeRemovedFromDocument', onRemovedFromDocument, true);
}, 1);
}, false);
// Whenever an element is inserted into document, listen for
// simple event named 'focus'.
function onInsertedIntoDocument(e) {
var elt = e.target;
if (elt.nodeType === 1)
elt.addEventListener('focus', onfocus, false);
}
function onRemovedFromDocument(e) {
var elt = e.target;
if (elt.nodeType === 1)
removeOnFocus(elt);
}
function onfocus(e) {
// In Chrome, caller is null if the user initiated the focus,
// and non-null if the focus was caused by a call to element.focus().
var causedByUser = (onfocus.caller == null);
console.log('onfocus ' + e.target.nodeName +
': caused by user? ' +causedByUser +
(e.target.autofocus ? ' autofocus' : ''));
if (! causedByUser) {
e.target.blur();
}
}
// Clean up by removing all the 'focus' event listeners.
function removeOnFocus(elt) {
elt.removeEventListener('focus', onfocus, false);
for (var i = 0; i < elt.children.length; i++)
removeOnFocus(elt.children[i]);
}
這manifest.json的:
{
"name": "unfocus",
"version": "1.0",
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["unfocus.js"],
"run_at": "document_start"
}
]
}
感謝您的回答。我看到有很多事情我不瞭解js中的事件。我沒有時間去測試這些,我可能暫時沒有時間,但是當我看到它的時候我會報告回來。 – inconvergent