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

无法获取rect的offset值,如何获取鼠标在rect上的相对位置?

解决SVG中rect元素相对鼠标位置获取问题

问题出在SVG元素的offsetX/offsetY是相对于SVG视口而非元素自身的。要获取鼠标相对于rect的位置,需要通过元素的边界矩形计算:

解决方案代码

<svg width="500" height="100" style="border: 1px solid black">
  <rect x="50" fill="#ccc" width="100" height="100"></rect>
</svg>
const rect = document.querySelector('svg rect')
rect.addEventListener('mousemove', (event)=>{
  // 获取rect元素在页面中的边界信息
  const rectBounds = rect.getBoundingClientRect();
  // 计算鼠标相对于rect左上角的位置
  const relativeX = event.clientX - rectBounds.left;
  const relativeY = event.clientY - rectBounds.top;
  
  console.log(relativeX); // 鼠标在rect左侧时会输出负数,比如-1
})

原理说明

  • getBoundingClientRect()返回元素相对于浏览器视口的位置和尺寸信息(left、top、width、height等)。
  • event.clientX/event.clientY是鼠标相对于浏览器视口的坐标。
  • 两者相减就能得到鼠标相对于rect元素左上角的偏移量,超出元素范围时会出现负数(左侧/上方)或大于元素尺寸的数值(右侧/下方)。

内容的提问来源于stack exchange,提问作者Luan Correia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 10:29:55