停止所有孩子的点击事件传播

时间:2017-02-08 03:35:31

标签: javascript angular

如何停止所有子元素的click事件传播:

<div (click)="openModal()">
    <span>Click in this element open the modal</span>
    <li>Click in this element open the modal too</li>
    <p>Click in this element open the modal too</p>
    <input type="button">Click in this element open the modal too</input>
</div>

我想只使用div元素打开模态。有办法吗?

1 个答案:

答案 0 :(得分:10)

如果要在单击父div元素时有条件地执行逻辑 (而不是在单击子元素时传播事件时),那么您可以查看如果事件的currentTarget property等于target property

因此,如果您只想过滤掉单击子元素并且您希望过滤掉传播事件的实例,那么您可以检查$event.currentTarget是否等于$event.target

public openModal ($event) {
  if ($event.currentTarget === $event.target) {
    // Clicked on the parent `div` element with the
    // click event binding `(click)="openModal($event)"`
    console.log('Clicked the parent, not the child.');
  }
}
<div (click)="openModal($event)">
  <span>...</span>
  <p>...</p>
</div>
相关问题