You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

堆叠元素点击事件处理:上层保交互同时触发下层子元素点击

问题描述

页面结构为 wrapper-div 下包含 child-div#1 与 child-div#2,child-div#2 内部有 grandchild-div#1:

  • child-div#1 设置 zIndex: 1,内部包含需要保留交互能力的 textarea
  • child-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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 12:55:18