子级 <div> 元素离开父级 <div> 元素

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

我希望父元素内的子元素跟随鼠标光标仅到达父元素边界所在的位置,并停在那里而不超出它

main = document.getElementById("bar_2")
ball = document.getElementById("ball")        

main.addEventListener("pointermove", (event => {
  const rect = main.getBoundingClientRect();

  ball.style.left = (event.clientX - rect.left) + "px"
  ball.style.top = (event.clientY - rect.top) + "px"
  ball.style.transform = "translate(-50%, -50%)"
}))
html::-webkit-scrollbar{
  width: 0;
}

body{
  margin: 0%;
  background-color: #1c1a1b;
  display: flex;
  flex-direction: column;

  color: #cccccc;
}

#bar_1{
  height: 7.5vh;
  background-color: #1c1a1b;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

#bar_3{
  height: 7.5vh;
  background-color: #1c1a1b;
  display: flex;
  flex-direction: column;
}

#bar_2{
  max-height: fit-content;
  min-height: 90vh;
}

#ball{
  position: relative;
  width: 50px;
  height: 50px;
  border-style: solid;
  border-radius: 50px;
}
<div id="bar_1">
</div>
<div id="bar_2">                 
  <div id="ball"></div>
</div>
<div id="bar_3"></div>

所以如果我将鼠标光标保持在 bar_1 上,球将出现在 bar_1 处,但我希望它停在 bar_2 的边缘

javascript html css
1个回答
0
投票

“ball”元素被允许移动到其父容器的边界之外,因为它的移动没有限制,因此它可以跟随鼠标超出“bar_2”的边界。我将球的位置更改为绝对位置,然后更改了一些 JS,以便跟踪鼠标移动并且仅在“bar_2”容器内移动。

    #ball {
  position: absolute; /* Changed this to absolute */
  width: 50px;
  height: 50px;
  border-style: solid;
  border-radius: 50%;
}

    main.addEventListener("pointermove", (event) => {
       const rect = main.getBoundingClientRect();

  // This calculates the mouse's position relative to bar_2.
  let x = event.clientX - rect.left;
  let y = event.clientY - rect.top;

  // I have implemented this logic to make sure the ball's x and y positions stay within the boundaries of bar_2.
  x = Math.max(0, Math.min(x, rect.width - ball.offsetWidth));
  y = Math.max(0, Math.min(y, rect.height - ball.offsetHeight));

  // Sets the ball's position inside the bar_2 container based on the coordinates of x and y, centering the ball on the mouse.
  ball.style.left = `${x}px`;
  ball.style.top = `${y}px`;
  ball.style.transform = "translate(-50%, -50%)";
});
© www.soinside.com 2019 - 2024. All rights reserved.