在 JavaScript 中检测焦点丢失

问题描述 投票:0回答:2

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

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

与 MSIE 相比——几乎所有类型的元素都接收 模糊事件——Gecko 浏览器上的几乎所有类型的元素都不起作用 通过这次活动。

哪些元素会/不会与此一起工作,有没有更好的方法来检测这些事情?

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

javascript html dom
2个回答
4
投票

您可以在 body 元素上使用

onfocusout
onblur
onfocusout
之间的区别在于后者会冒泡,因此您不必为您想要的每个节点安装它。

相关问题:使用 JavaScript 或 jQuery 检测哪个表单输入具有焦点


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

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

© www.soinside.com 2019 - 2024. All rights reserved.