2

我希望能够检测到任意元素何时在 JavaScript 中失去焦点,因此我可以构建一个类似于 jEdit 的内联编辑工具。这个库我不能依赖 jQuery,所以我需要一个本地方法来做它。

我查看了 onblur,这似乎是正确的,但 MDN 有一个注释表明它可能是 IE 特定的?

与几乎所有类型的元素都会接收到模糊事件的 MSIE 相比,Gecko 浏览器上的几乎所有类型的元素都不适用于此事件。

哪些元素将/不会与此一起使用,有没有更好的方法来检测这些东西?

如果模糊有效,是否应该更改https://developer.mozilla.org/en-US/docs/DOM/element.onblur上的文档?

4

2 回答 2

2

您可以onfocusout在 body 元素上使用一个。onblur和之间的区别在于onfocusout后者会冒泡,因此您不必为所需的每个节点都安装它。

但是onfocusout不是跨浏览器,是 IE 的特性,不是标准。我不知道onblur在当前浏览器中设置有什么问题,除了它不会冒泡。

每当发生模糊时,唯一要通知的 hack 是让您document.activeElement在看到更改时轮询和触发事件。请参阅使用 JavaScript 或 jQuery 检测哪个表单输入具有焦点

于 2012-09-18T23:21:39.040 回答
0

为了检测焦点的丢失,对于可访问性审计,我个人使用以下所有丑陋的组合:

(function($){

var focusCounter = 0;

/* Set focus outline (CSS, jQuery): */
$("*").on("focus","body",function(e){$(e.target).css("outline","5px solid orange");$(e.target).on("blur",function(e){$(e.target).css("outline","none");})});

/* Log keypress */
$(document).on('keydown',function(e){
    console.log("========= KEYDOWN ", e.key, " ==================");
});

/* Log currently focused element (On start) */
console.log("CURRENT: ",document.activeElement);

/* Log focused element (On focus) */
document.addEventListener("focus",function(){
    console.log(
        "[ " + (focusCounter++).toString() + " ]",
        "FOCUSED: ",
        "<" + document.activeElement.nodeName + ">",
        ($.trim($(document.activeElement).text())? $.trim($(document.activeElement).text()) : $.trim($(document.activeElement).val())).replace(/(\r\n|\n|\r)/gm, "").substring(0, 30) + '...',
        document.activeElement
    );

},true);

/* Try to detect loss of focus (Works in Chrome) */
document.addEventListener("focusout", function(event){console.log((!event.relatedTarget)?"⚠ FOCUS LOST":"");});

/* Fallback, checks in intervals if the focus is still active/lost e.g. if onfocus or onfocusout didn't work */
(function(){setInterval(function(){console.log('interval check: ',(document.body===document.activeElement)?"FOCUS LOST":"ok");},8500);})();

})(jQuery);

想法:我将所有这些设置为书签,以便我可以轻松访问它

于 2021-10-28T09:31:31.180 回答