JavaScript 侦听所有焦点/模糊事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21572434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:13:20  来源:igfitidea点击:

JavaScript listen for all focus/blur events

javascriptjqueryevents

提问by alt

So I'd like some JavaScript which listens for all potentialfocus/blur events on the page. I can do this for click events quite easily:

所以我想要一些 JavaScript 来监听页面上所有潜在的焦点/模糊事件。我可以很容易地为点击事件做到这一点:

document.addEventListener('click', function (e) { console.log('click!') })

Any time any element is clicked, the event will trigger, even if the node was inserted after the event listener was added.

任何时候点击任何元素,事件都会触发,即使节点是在添加事件侦听器之后插入的。

I'd like to do the same for focus events, but they are only triggered on individual elements, and never bubble up to the document.

我想对焦点事件做同样的事情,但它们只在单个元素上触发,永远不会冒泡到文档。

How can I accomplish this? Is the only way to walk the DOM every few seconds and re-listen in case a new input element has been added?

我怎样才能做到这一点?是每隔几秒钟遍历一次 DOM 并在添加新输入元素时重新侦听的唯一方法吗?

回答by Arun P Johny

You can use the focusinand focusoutevents which bubbles up.

您可以使用冒泡的 focusinfocusout事件。

document.addEventListener('focusin', function(e) { console.log('focusin!')})

Demo: Fiddle

演示:小提琴