它可以像Chrome和MSIE中预期的那样工作。出于某种原因,事件触发内部矩形元素以及SVG元素(我认为)。这里是酱(这是整个页面):为什么在Firefox中闪烁?
<html>
<body>
<svg width="400" height="400" style="overflow: hidden; border: 1px solid gray" id="mySVG">
<rect x="10" y="10" width="100" height="100" fill="red" id="myRect"></rect>
</svg>
<script>
svg = document.getElementById('mySVG');
rect = document.getElementById('myRect');
svg.onmousemove = function (e)
{
if (e.currentTarget.toString().indexOf('SVGSVGElement') >= 0) {
var x = e.offsetX,
y = e.offsetY;
if (x && y) {
console.log(x)
rect.setAttribute('x', x - 50);
rect.setAttribute('y', y - 50);
}
}
};
</script>
</body>
</html>
但事件处理程序绑定到SVG元素 - 所以它会在鼠标围绕SVG元素移动时触发 - 所以不应该将offsetX和offsetY作为鼠标相对于坐标的坐标 - 就像它们在Chrome中一样MSIE(11)?即使鼠标超过了矩形,是否可以获得与整个画布相关的偏移量?这是通过offsetParents并添加X和Y坐标的问题吗? – Richard
事件处理程序被绑定到'svg',但是在'rect'上发生的事件一直冒泡到'svg'。 'e.target'为你提供事件发送的原始元素,'e.currentTarget'是处理程序所连接的元素。 – ccprog
改为使用offsetParent/offsetLeft和offsetTop代替:https://www.rgraph.net/tests/svg-getmousexy.html – Richard