CSS实现父div不可点击、子元素可点击,且可穿透点击底层div
实现顶层容器点击穿透,同时保留子元素可点击
这个需求其实用CSS的pointer-events属性就能完美解决,我直接给你上可运行的代码和解释:
完整代码示例
<!DOCTYPE html> <html> <head> <style> #background { background-color: #f33; width: 250px; height: 250px; position: fixed; top: 0; left: 0; z-index: -1; } #top { width: 250px; height: 250px; position: fixed; top: 0; left: 0; pointer-events: none; /* 核心:让顶层容器不拦截点击 */ } .children { width: 80px; height: 80px; position: relative; pointer-events: auto; /* 让子元素恢复可点击 */ margin: 10px; } .blue { background-color: #33f; } .green { background-color: #3f3; } </style> </head> <body> <div id="background" onclick="bgclick()"></div> <div id="top"> <div class="children blue" onclick="topclick()"></div> <div class="children green" onclick="topclick()"></div> </div> <script> function bgclick() { console.log('Background Is Clicked!'); } function topclick() { console.log('Top Child Is Clicked!'); } </script> </body> </html>
关键原理说明
- 给
#top添加pointer-events: none:这个属性会让整个顶层容器不接收任何鼠标交互事件,点击它的空白区域时,事件会直接穿透到下面的#background元素。 - 给
.children添加pointer-events: auto:这个值会覆盖父元素的none设置,让子元素重新获得接收鼠标事件的能力,点击蓝色/绿色方块时就能正常触发topclick函数。 - 底层的
#background虽然z-index: -1,但只要顶层元素不拦截点击,它依然能响应点击事件。
测试一下:点击红色区域(顶层容器的空白处)会打印Background Is Clicked!,点击蓝色或绿色方块会打印Top Child Is Clicked!,完全符合你的需求~
内容的提问来源于stack exchange,提问作者Seb D
相关产品推荐
相关产品推荐

