【问题标题】:Why is my focus/blue event listener not triggering?为什么我的焦点/蓝色事件监听器没有触发?
【发布时间】:2020-04-18 02:53:35
【问题描述】:

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

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 中观察时,我可以看到我的听众正在注册,点击我的元素,我可以看到focusblur 都被钩住了,但不会触发。

我对@9​​87654326@ 做了类似的事情,而且效果很好,那么focusblur 是怎么回事?下面的块工作......

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

【问题讨论】:

  • 确保在ngAfterViewInit中添加了事件监听器。
  • 您是否有理由手动添加事件侦听器而不是在 HTML 中绑定?你能显示所有相关的代码吗?我想说手动绑定事件侦听器并不是必然错误,但在 Angular 中绝对是时髦的。
  • @KurtHamilton 你是对的,我会使用(focusin)(focusout) 但真正的原因是缺少tabindex

标签: javascript angular typescript dom-events


【解决方案1】:

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

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

我所有的代码都使用tabindex

【讨论】:

    猜你喜欢
    • 2015-08-18
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    • 1970-01-01
    • 1970-01-01
    • 2011-03-03
    • 2022-01-16
    相关资源
    最近更新 更多