Javascript:全局元素焦点侦听器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15882045/
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 02:26:55  来源:igfitidea点击:

Javascript: Global Element Focus Listener

javascript

提问by ryandlf

I am trying to set a listener that listens for all focus events. In particular I am trying to listen for anytime an input or textbox gains focus. Per some research, the widely accepted way to achieve this is like this:

我正在尝试设置一个侦听所有焦点事件的侦听器。特别是我试图在输入或文本框获得焦点的任何时候收听。根据一些研究,实现这一目标的广泛接受的方法是这样的:

document.body.onfocus = function(event) {
   //Check the event.target for input/textbox
   //Do something
};

But the document.body.onfocus doesn't seem to fire, ever. I thought it might be because the document doesn't actually ever receive focus so I tried:

但是 document.body.onfocus 似乎永远不会触发。我认为这可能是因为该文档实际上从未获得焦点所以我尝试过:

document.body.focus();

To initially "set" the focus, but this doesn't work either.

最初“设置”焦点,但这也不起作用。

Any ideas on how I can listen to a focus event on all inputs/textboxes without actually setting the event directly on the element itself? Vanilla javascript only please, I am not using a framework.

关于如何在所有输入/文本框上收听焦点事件而不实际直接在元素本身上设置事件的任何想法?请只使用 Vanilla javascript,我没有使用框架。

Per the accepted answer here is some working code:

根据这里接受的答案是一些工作代码:

var focusHandler = function(event) {
    var type = event.target.nodeName.toLowerCase();
    if(type == 'input' || type == 'textarea') {
        //Do something
    }
};
document.body.addEventListener('focus', focusHandler, true); //Non-IE   
document.body.onfocusin = focusHandler; //IE

采纳答案by user1983983

As some events (focus, blur, change) do not bubble up, I would recommend you to try Event Capturinginstead. First of all onfocuswill not work for this, so you have to use addEventListenerwhere you are able to specifiy the used delegation mode in the third argument. Look at MDNfor the use of addEventListener.

And take a look at this articlefor further information about delegating the focus event up.

由于某些事件(焦点、模糊、变化)不会冒泡,我建议您尝试一下Event Capturing。首先onfocus不会为此工作,因此您必须使用addEventListener能够在第三个参数中指定使用的委托模式的地方。查看MDN以了解addEventListener.

并查看本文以获取有关将焦点事件委派的更多信息。

回答by T.J. Crowder

The focuseventdoesn't bubble from elements up to their ancestor elements, so you can't use event delegation (hooking it on bodyand seeing it for all descendants of body) to detect it.

focus事件不会从要素泡了他们的祖先元素,所以你不能使用事件代表团(钩住它body,看到它的所有后代body)检测到它。

There's a newer event, focusin(a Microsoft innovation, now also available in other browsers), which does bubble, so that may work for you depending on which browsers you want to support.

有一个较新的事件focusin(Microsoft 创新,现在也可在其他浏览器中使用),它确实会冒泡,因此根据您要支持的浏览器,它可能对您有用。