使用以下示例:
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
是父母的孩子。有没有办法解决这个问题?
答案 0 :(得分:7)
使用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>
答案 1 :(得分:1)
您必须使用.stopPropagation()
来处理该事件。
.parent {
align-items: center;
background: blue;
display: flex;
justify-content: center;
}
.child {
background: pink;
height: 100px;
width: 200px;
}
&#13;
<div class="parent" onclick="alert('I am parent')">
<div class="child" onclick="event.stopPropagation()"></div>
</div>
&#13;