堆叠元素点击事件处理:上层保交互同时触发下层子元素点击
问题描述
页面结构为 wrapper-div 下包含 child-div#1 与 child-div#2,child-div#2 内部有 grandchild-div#1:
child-div#1设置zIndex: 1,内部包含需要保留交互能力的textareachild-div#2是position:absolute元素,尺寸与child-div#1相同且位于其后方- 核心需求:捕获
grandchild-div#1的点击事件,但它被child-div#1遮挡;此前尝试给child-div#1设置pointer-events: none,但会丢失内部textarea的交互能力,无法满足需求
解决方案
给 child-div#1 设置 pointer-events: none,同时给内部的输入框(textarea/input)单独设置 pointer-events: auto。这样既让下方的 grandchild-div#1 能穿透上层接收点击事件,又能保留输入框的正常交互。
修正后的代码
app.js
import { useState } from 'react'; const App = () => { const [value, setValue] = useState("test [string]"); const words = value.split(' '); return ( <div className="wrapper"> <div className="text-area-container"> <input className="input" value={value} onChange={(e) => setValue(e.target.value)} type="text" /> </div> <div className="renderer"> {words.map((word, i) => ( <span key={i} className="grandchild" onClick={() => alert(`点击了单词:${word}`)} > {word} </span> ))} </div> </div> ); }; export default App;
app.css
.wrapper { position: relative; width: 300px; } .text-area-container { z-index: 1; position: relative; /* 上层容器不拦截指针事件,让下方元素可接收点击 */ pointer-events: none; } .input { width: 100%; resize: none; /* 输入框恢复指针事件,保留交互能力 */ pointer-events: auto; padding: 8px; box-sizing: border-box; } .renderer { width: 100%; position: absolute; inset: 0; padding: 8px; box-sizing: border-box; } .grandchild { margin-right: 4px; cursor: pointer; color: blue; text-decoration: underline; }
内容的提问来源于stack exchange,提问作者jasjamjos
相关产品推荐
相关产品推荐

