用下面的例子:
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
是父母的孩子。有什么办法可以克服这个吗?
Use event.stopPropagation() https://developer.mozilla.org/en/docs/Web/API/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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)