无法获取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
相关产品推荐
相关产品推荐

