Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

109
Visualizações
Div does not follow Mouse due to parent div

I have a problem where the mouse does not follow the div closely due to parent div left and top. Assume parent.jsx is developed by another developer, and I solely can control child.jsx, is there a way for me to make the div follow the mouse?

Here's the parent jsx

import "./styles.css";
import Child from "./child";


export default function Parent() {


  return (
    <div
      style={{
        top: "25px",
        left: "20px",
        position: "relative"
      }}
    >
      <Child />
    </div>
  );
}

The child jsx

import "./styles.css";
import { useRef } from "react";

export default function Child() {
  const descBox = useRef(null);
  const handleMove = (e) => {
    console.log(e.clientX, e.clientY);
    descBox.current.style.left = `${e.clientX}px`;
    descBox.current.style.top = `${e.clientY}px`;
  };
  return (
    <>
      <div
        onMouseMove={handleMove}
        style={{
          height: "300px",
          width: "100%",
          backgroundColor: "red"
        }}
      ></div>
      <div className="dropdown1" ref={descBox}>
        123asdfsfdafffasdfasfdsajkj
      </div>
    </>
  );
}

The css for child

.dropdown1 {
  position: absolute;
  left: 150px;
  top: 10px;
  background: #2b4557;
  padding: 4px 8px;
  font-size: 12px;
  line-height: 18px;
  color: #fff;
}

Codesandbox to run the code.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As the child is positioned absolute within the relative positioned parent you can work out its left and top positions relative to the parent and use those.

This code adds a small offset to give a slight gap between the cursor and the child (which you may or may not want).

const handleMove = (e) => {
  const rect = e.target.getBoundingClientRect();
  const x = e.clientX - rect.left + 10;
  const y = e.clientY - rect.top + 10;
  descBox.current.style.left = `${x}px`;
  descBox.current.style.top = `${y}px`;
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda