简体   繁体   English

如何将事件监听器添加到没有tabindex = 0的div中?

[英]How to add event listener to div without tabindex=0?

I have something like this control: 我有这样的控件:

在此处输入图片说明

I need to track focus on any element inside this control. 我需要关注此控件内的任何元素。 If I focus input or If I focus (click) calendar icon, I want to know that focus performed. 如果我聚焦输入或如果我聚焦(单击)日历图标,我想知道所执行的聚焦。

My idea is to add click listener on wrapper of input + calendar trigger. 我的想法是在输入+日历触发器的包装上添加点击监听器。 It is some div. 是一些div。

Out of the box I can't add focus listener to the div. 开箱即用,我无法将焦点侦听器添加到div。 To achieve this I need to add tabindex=0 to this div. 为此,我需要在该div中添加tabindex=0 This method will work, but it has one minus. 此方法可以使用,但是要减去一。

For example, I have form with many controls. 例如,我有很多控件的窗体。 Example code is below: 示例代码如下:

<div class="container">
  <input onfocus="onFocus()" />
  <div tabindex="0" onfocus="onFocus()">some div</div>
  <div tabindex="0" onfocus="onFocus(event.target)">
    <input onfocus="onFocus()" />
  </div>
  <input onfocus="onFocus()" />
</div>

When I focus first input and start looping through TAB key I want this behavior: focus calendar icon, focus next input, focus next calendar icon etc. But with tabindex=0 I break this behaviour. 当我关注第一个输入并开始通过TAB键循环浏览时,我想要这样的行为:关注日历图标,关注下一个输入,关注下一个日历图标等。但是使用tabindex=0我会破坏这种行为。 You can check it in this pen . 您可以用这支笔检查它。 You can see this broken behaviour after some div block. 您可以在some div块后看到这种损坏的行为。

Well, I have another option to add listener specifically for input and calendar icon (or any other icon). 好吧,我还有另一个选择可以专门为输入和日历图标(或任何其他图标)添加侦听器。 The problem is I have dynamic amount of icons on each field. 问题是我在每个字段上都有大量的图标。 And I have to add focus listener for each. 而且我必须为每个添加焦点侦听器。 Much simpler for me (and another developers) is the way when I have only one focus listener on the top (as I think). 对于我(和另一位开发人员)来说,最简单的方法是当我只在顶部放置一个焦点侦听器时(我认为)。

Is it somehow possible to add ability to add focus listener to the div without breaking focus loop (like I shown on the codepen example). 是否可以在不破坏焦点循环的情况下增加向div添加焦点侦听器的功能(如我在codepen示例中所示)。

Use element.addEventListener('focusin', handler) . 使用element.addEventListener('focusin', handler) focus and blur don't bubble, focusin and focusout do. focusblur不会冒泡, focusinfocusout不会冒泡。

 document.querySelector('.container') .addEventListener('focusin', function(event) { console.log(event.target) }) 
 <div class="container"> <input name="a" /> <div contenteditable="true">some div</div> <div> <input name="b" /> </div> <input name="c"/> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM