【问题标题】:Capture click event on parent container but not child捕获父容器而不是子容器上的单击事件
【发布时间】:2017-02-03 10:52:20
【问题描述】:

下面的例子:

HTML:

<div class="parent" onclick="alert('hello!')">
  <div class="child"></div>
</div>

CSS:

.parent {
  align-items: center;
  background: blue;
  display: flex;
  justify-content: center;
}

.child {
  background: pink;
  height: 100px;
  width: 200px;
}

我希望onclick 事件在用户单击父/蓝色部分时触发。但不是当用户点击子/粉红色部分时。现在,即使单击粉红色,事件也会触发,这当然是显而易见的,因为 .child 是父级的子级。有什么办法可以克服吗?

【问题讨论】:

标签: javascript html css


【解决方案1】:

使用event.stopPropagation() 方法将事件冒泡到 DOM 树。

.parent {
  align-items: center;
  background: blue;
  display: flex;
  justify-content: center;
}
.child {
  background: pink;
  height: 100px;
  width: 200px;
}
<div class="parent" onclick="alert('hello!')">
  <div class="child" onclick="event.stopPropagation()"></div>
</div>

【讨论】:

    【解决方案2】:

    您必须为该事件使用.stopPropagation()

    .parent {
      align-items: center;
      background: blue;
      display: flex;
      justify-content: center;
    }
    .child {
      background: pink;
      height: 100px;
      width: 200px;
    }
    <div class="parent" onclick="alert('I am parent')">
      <div class="child" onclick="event.stopPropagation()"></div>
    </div>

    【讨论】:

    • 不是副本,我不能和别人打的一样吗?
    • 有些问题可能有相似或只有一个答案
    • 是的,我明白了,但我想到了相同的答案和 stopPropagation() 让孩子不要触发父母的事件。
    猜你喜欢
    • 2021-06-27
    • 2021-06-01
    • 2016-07-23
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多