如何用JavaScript阻止.box1/.box2点击事件且不改变鼠标样式
解决方案
核心处理逻辑
- 事件拦截:在父元素
wrap的点击事件中,判断点击目标是否属于.box1或.box2区域,若是则跳过后续逻辑,精准阻止这两个区域的点击响应。 - 光标统一:给
.box1和.box2设置cursor: inherit,继承父元素的光标样式,避免鼠标移上去时光标变化。
修改后的完整代码
HTML(保持不变)
<div class="wrap"> <div class="boxs"> <div class="box1"></div> <div class="box2"></div> </div> </div>
CSS
.wrap { width: 500px; height: 500px; background-color: lightcyan; cursor: pointer; } .boxs { width: 300px; border: 2px solid black; } .box1 { width: 250px; height: 250px; background-color: bisque; cursor: inherit; /* 继承父元素光标样式 */ } .box2 { width: 250px; height: 250px; background-color: azure; cursor: inherit; /* 继承父元素光标样式 */ }
JavaScript
const wrap = document.querySelector('.wrap'); wrap.addEventListener('click', (event) => { // 检查点击目标是否在.box1或.box2范围内(包括子元素) if (event.target.closest('.box1, .box2')) { return; // 不执行wrap的点击逻辑 } console.log('wrap'); });
关键说明
closest('.box1, .box2')会遍历点击目标的所有父元素,只要其中有匹配.box1或.box2的元素,就判定为点击了需要阻止的区域,后续即使给这两个盒子加子元素也能生效。- 移除了
pointer-events: none,避免点击穿透导致的意外触发;用cursor: inherit保证光标样式和父元素一致,解决光标变化的问题。
内容的提问来源于stack exchange,提问作者JackFan
相关产品推荐
相关产品推荐

