首页 > 解决方案 > Blur event is not triggering in IE - Angular 2+

问题描述

The below problem is related to Blur not working - Angular 2 thread.

I have a shared component of custom select and I am trying to add a blur event to close when the component is not in focus.

// HTML

<div (blur)="closeDropDown()" tabindex="0">
  <span (click)="selectClicked()" class="placeholder">
    Select Item 
  </span>
  <div class="options">
    <ul>
       <li *ngFor="let item of data"> 
       <span>{{item}}</span></li>
    </ul>
  </div>

//TS

 selectClicked() {
   this.dropdownOpen = true;
 }

 closeDropDown() {
   this.dropdownOpen = false;
 }

I was able to implement the blur event by adding the tabindex mentioned in the thread(works in all browsers except IE). But blur event is not firing in IE(version > 10).

I tried to use focusout instead of blur but the selected value is not getting attached to the custom select and requires many selections to select an option.

Why does blur is not triggering on div and are there any alternatives that I can use on block level elements?

标签: javascriptangulartypescriptinternet-explorerblur

解决方案


我能够通过将 focusout 和 tabindex=-1 添加到 div 元素来解决问题。但是通过这样做,这个值并没有被设置为我的自定义下拉列表。

原因是当我使用 focusout 时,事件正在冒泡返回父级,并且在选择后需要更多时间来设置下拉值。

所以我错过了停止冒泡事件,解决方法是停止传播。

// html
<div (focusout)="closeDropDown($event)" tabindex="-1"></div>

// ts
closeDropDown(event) {
  event.stopPropogation();
  this.dropdownOpen = false;
}

当元素即将失去焦点时会触发 focusout 事件。此事件与模糊之间的主要区别在于,聚焦气泡会出现,而模糊不会。

在 blur vs focusout 上找到更多相关信息——有什么真正的区别吗?https://developer.mozilla.org/en-US/docs/Web/API/Element/focusout_event


推荐阅读