用下面的例子:
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
是父级的子级。有什么办法可以克服这个问题吗?
最佳答案
使用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>
关于javascript - 捕获父容器而不是子容器的点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42022540/