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

Div高度调整致位置偏移:鼠标控制旋转线条缩放异常修复求助

问题修复方案

问题出在.angle元素的定位和变换原点设置上:当前它以自身底部为旋转中心,且初始位置位于.line的顶部,导致高度变化时线条会围绕自身底部偏移,而非从坐标轴原点(中心)向外延伸。

修复步骤:

  • 调整.angle的定位,使其中心与坐标轴原点(.line的中心)重合
  • 修改变换原点为自身中心,确保旋转和高度变化都围绕原点进行
  • 微调旋转角度计算,让线条精准指向鼠标位置

修改后的完整代码:

HTML

<div class="line">
  <div class="angle"></div>
</div>

CSS

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  height: 100%;
  width: 100%;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
}

.line {
  height: 75%;
  width: 2px;
  background: #000;
  position: absolute;
}

.line::before {
  content: '';
  position: absolute;
  height: 100%;
  width: 100%;
  background: #000;
  rotate: 90deg;
}

.angle {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transform-origin: center;
  height: 190px;
  width: 2px;
  background: red;
}

JavaScript

let x = document.body.clientWidth / 2;
let y = (document.body.clientHeight || document.documentElement.clientHeight) / 2;

let ang = document.querySelector(".angle");

document.addEventListener("mousemove",(e)=>{
  let thetaRadians = Math.atan2(e.clientY - y, e.clientX - x);
  let thetaDegrees = thetaRadians * (180 / Math.PI);
  ang.style.rotate = `${thetaDegrees}deg`;
  
  const distance = Math.floor(Math.sqrt(Math.pow((e.clientX - x),2) + Math.pow((e.clientY - y),2)));
  ang.style.height = `${distance}px`;
});

核心修改说明:

  1. position: absolute + translate(-50%, -50%)让.angle的中心精准对齐坐标轴原点
  2. transform-origin: center确保高度增减时,线条从原点向外延伸/缩短,不会偏移
  3. 移除旋转角度的+90deg修正,atan2计算出的角度可直接让线条指向鼠标位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 11:23:18