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

React+Tailwind网格布局中两个Div层级异常问题求助

问题解决:拖拽图片被右侧容器遮挡

原因分析

你没设置z-index但出现遮挡,核心是CSS堆叠上下文的默认规则:在同一层级的兄弟元素中,后出现的元素(右侧div)会在堆叠顺序上高于先出现的(左侧div)。你的图片是绝对定位在父div内部,继承了父容器的堆叠层级,所以拖拽左侧图片到右侧区域时,会被层级更高的右侧父div挡住。

解决方案

给拖拽的图片添加framer-motion的whileDrag属性,在拖拽过程中提升它的z-index,让它脱离父容器的堆叠限制:

修改后的代码

import { motion } from "framer-motion";

return (
  <div className="grid grid-cols-2">
    <div className="border border-white w-full rounded-l-3xl bg-self grid">
      {oneLeftImg && oneLeftImg.url !== defaultImage && (
        <motion.img
          src={oneLeftImg.url}
          alt={oneLeftImg.name}
          className="justify-self-center self-center absolute max-h-[90%]"
          drag
          whileDrag={{ zIndex: 10 }} // 拖拽时提升层级
        />
      )}
      <button
        className="text-gray-400 text-2xl h-6 justify-self-end mr-2 mt-2"
        onClick={() => handleRemoveClick("oneLeft")}
      >
        <BsFillDashCircleFill />
      </button>
      <label htmlFor="uploadoneLeft" className="justify-self-center">
        <BsUpload className="text-4xl text-gray-400 justify-self-center" />
        <input
          type="file"
          id="uploadoneLeft"
          onChange={(e) => handleImageUpload(e, "oneLeft")}
        />
      </label>
    </div>
    <div className="border border-white w-full rounded-r-3xl bg-self grid">
      {oneRightImg && oneRightImg.url !== defaultImage && (
        <motion.img
          src={oneRightImg.url}
          alt={oneRightImg.name}
          className="justify-self-center self-center absolute max-h-[90%]"
          drag
          whileDrag={{ zIndex: 10 }} // 拖拽时提升层级
        />
      )}
      <button
        className="text-gray-400 text-2xl h-6 justify-self-end mr-2 mt-2"
        onClick={() => handleRemoveClick("oneRight")}
      >
        <BsFillDashCircleFill />
      </button>
      <label htmlFor="uploadoneRight" className="justify-self-center">
        <BsUpload className="text-4xl text-gray-400" />
        <input
          type="file"
          id="uploadoneRight"
          onChange={(e) => handleImageUpload(e, "oneRight")}
        />
      </label>
    </div>
  </div>
);

补充说明

如果不想依赖framer-motion的状态,也可以给两个父容器统一设置相同的z-index: 1,然后给图片默认设置z-index: 2,这样图片始终在父容器上方,拖拽时也不会被兄弟容器遮挡。不过用whileDrag更灵活,只有拖拽时才提升层级,避免不必要的层级覆盖。

内容的提问来源于stack exchange,提问作者RhaenyraLiang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 03:47:44