如何在react中动态获取div的位置?

问题描述 投票:0回答:1

我一直在尝试创建一种与此类似的效果: 每当一个 div 悬停时,一个更大的 div 会覆盖它,显示有关该卡的更多详细信息。 这是jsx代码(所有类都是Tailwind css类):

import "../../App.css";
import { useState, useRef } from "react";

function List() {
  const cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
  return (
    <div>
      <h2 className="text-white pl-[4%] text-[1.3vw] font-semibold">
        List Heading
      </h2>
      <div className="flex space-x-2 pt-[1%] pl-[4%] overflow-x-scroll overflow-y-hidden">
        <Card num="1" />
        <Card num="2" />
        <Card num="3" />
        <Card num="4" />
        <Card num="5" />
        <Card num="6" />
        <Card num="7" />
        <Card num="8" />
        <Card num="9" />
        <Card num="10" />
      </div>
    </div>
  );
}

function Card(props) {
  const [classes, setClasses] = useState("bg-yellow-300 h-[8.6vw] w-[15vw]");
  const divRef = useRef();
  function cardHovered() {
    const rect = divRef.current.getBoundingClientRect();
    let posX = rect.x;
    let posY = rect.y;
    console.log("x-axis: " + posX);
    console.log("y-axis: " + posY);
    setClasses(
      `h-[18vw] w-[22vw] bg-black opacity-50 z-10 absolute left-[${posX}px] top-[${posY}px]`
    );
  }

  function cardUnhovered() {
    setClasses("hidden");
  }

  return (
    <div className={`flex justify-center items-center`}>
      <div
        ref={divRef}
        className={`bg-yellow-300 h-[8.6vw] w-[15vw]`}
        onMouseOver={cardHovered}
      >
        <p>{props.num}</p>
        <div className={`${classes}`} onMouseLeave={cardUnhovered}></div>
      </div>
    </div>
  );
}

export default List;

悬停时出现的 div 应该相对于悬停的 div 动态定位,但当 Flexbox 在 x 轴上滚动时不会发生这种情况。我怎样才能做到这一点?

javascript css reactjs react-hooks css-position
1个回答
0
投票

使用 tailwind CSS,您无法动态计算 className 字符串,例如

left-[${posX}px]

相反,您应该将

relative
位置添加到父(卡片)类名中,这样您就可以根据相对于父 div 位置的坐标来指定子元素(较大的封面 div)的位置 -
 className = "absolute top-0 left-0"
会将盖子元件定位在卡片的正上方,无论它在哪里。 CSS 将使两个元素的位置保持同步,因此不再需要以编程方式确定父 div 的位置。

© www.soinside.com 2019 - 2024. All rights reserved.