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

如何让子div元素在父div边界内跟随鼠标且不越界

子元素在父元素边界内跟随鼠标且不超出范围的实现方案

你的问题核心是未对鼠标相对坐标做边界限制,导致子元素会超出父元素范围。以下是修正后的实现:

核心思路

  1. 计算子元素(ball)的半宽高,结合translate(-50%, -50%)的偏移逻辑,确保子元素边缘不会超出父元素边界。
  2. 用Math.max()和Math.min()将鼠标相对坐标限制在父元素的有效范围内:
    • 水平方向:左不小于球半宽,右不大于父元素宽度减球半宽
    • 垂直方向:上不小于球半高,下不大于父元素高度减球半高

修改后的完整代码

HTML

<div id="bar_1"></div>
<div id="bar_2">                 
  <div id="ball"></div>
</div>
<div id="bar_3"></div>

CSS

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;
  border-bottom: 1px solid #444; /* 方便区分区域,可移除 */
}

#bar_3{
  height: 7.5vh;
  background-color: #1c1a1b;
  display: flex;
  flex-direction: column;
  border-top: 1px solid #444; /* 方便区分区域,可移除 */
}

#bar_2{
  min-height: 90vh;
  border: 1px solid #666; /* 方便区分区域,可移除 */
  position: relative; /* 明确子元素定位基准 */
}

#ball{
  position: relative;
  width: 50px;
  height: 50px;
  border: 2px solid #fff;
  border-radius: 50%;
}

JavaScript

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

// 预计算球的半宽高
let ballHalfWidth = ball.offsetWidth / 2;
let ballHalfHeight = ball.offsetHeight / 2;

main.addEventListener("pointermove", (event) => {
  const rect = main.getBoundingClientRect();
  // 鼠标在父元素内的相对坐标
  let relX = event.clientX - rect.left;
  let relY = event.clientY - rect.top;

  // 限制坐标范围,确保球不超出父元素
  relX = Math.max(ballHalfWidth, Math.min(relX, rect.width - ballHalfWidth));
  relY = Math.max(ballHalfHeight, Math.min(relY, rect.height - ballHalfHeight));

  // 设置球的位置
  ball.style.left = `${relX}px`;
  ball.style.top = `${relY}px`;
  ball.style.transform = "translate(-50%, -50%)";
});

// 窗口大小变化时更新球的半宽高(若球尺寸可能动态改变)
window.addEventListener("resize", () => {
  ballHalfWidth = ball.offsetWidth / 2;
  ballHalfHeight = ball.offsetHeight / 2;
});

额外说明

  • 给bar_2添加position: relative,明确子元素的relative定位基准,避免意外偏移。
  • 代码中的边框仅用于区分区域,实际使用时可根据需求移除。
  • 窗口resize监听用于确保边界限制在父元素尺寸变化时依然准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 07:59:51