首页 > 解决方案 > 为什么我的焦点/蓝色事件监听器没有触发?

问题描述

我不认为我在这里做错了什么或很时髦,但它不会触发什么……

const elm = (this.agGridElm.nativeElement as HTMLElement);
elm.addEventListener('focus', (focusEvent: FocusEvent) => {
  elm.classList.add('focused');
}, { capture: true, passive: true });

elm.addEventListener('blur', (focusEvent: FocusEvent) => {
  elm.classList.remove('focused');
}, { capture: true, passive: true });

我尝试使用或不使用第三个参数{ capture: true, passive: true },结果是一样的......奇怪的是,当我在 Chrome 调试器中观察时,我可以看到我的听众正在注册Event Listeners,点击我的元素,我可以看到两者focus并被blur迷住了,但是只是不会触发。

我做了类似的事情mouseleave并且完美地工作,那么focus和怎么了blur?下面的块工作......

elm.addEventListener('mouseleave', (mouseEvent: MouseEvent) => {
  console.log('Hi there!');
});

标签: javascriptangulartypescriptdom-events

解决方案


原来原因是因为focus,模糊,focusinfocusout元素上div,他们需要有一个tabindex焦点才能工作!解决方案是将以下内容添加到我希望收听的元素中。

<div tabindex="-1"></div>

我所有的代码都与tabindex


推荐阅读