结论:子元素绑定了 mousedown 和 click事件,在 mousedown事件中把父元素的 display设为 none,click事件将不会被触发
论证代码:
<div class="father">
<div class="child">child</div>
</div>
<script>
child = document.querySelector('.child')
father = document.querySelector('.father')
child.onmousedown = function(e) {
console.log('mousedown')
father.style.display='none'
}
child.onclick = function() {
console.log('click')
}
</script>
运行后,点击 child,控制台只会输出 mousedown
实践中踩坑经历:
做的编辑文档的页面,鼠标点击后可以多选剪切复制,所以监听了 document 的 mousedown事件,
因为可能有其他打开的功能框,所以在多选前,先关闭功能框,也就是 mousedown事件中第一步先把功能框的 display = 'none'
在点击确定后,意外触发了 document 的 mousedown 导致 display被设成 none,导致绑定给确定按钮的click 函数没有预期执行
最终解决方案:给确定按钮的 mousedown 添加了停止冒泡