javascript - 在 Firefox 中移动 SVG 元素失败

标签 javascript firefox svg

我正在尝试用鼠标拖动 SVG 中的框元素。 它在 Chrome/Chromium 中工作正常,但在 Firefox 中可以先工作,但后来失败。 您可以在 that site 中测试代码.

有什么方法可以让它在 Firefox 中运行吗?谢谢。

来源:

<html>
    <head>
        <meta charset="UTF-8">
        <title>Nodes</title>
        <script>
            'use strict';

            var node;
            var startX;
            var startY;

            function setup() {
                node = document.getElementById('node');
                node.addEventListener('mousedown', function(event) {
                    document.addEventListener('mousemove', move, false);
                    startX = event.clientX;
                    startY = event.clientY;
                }, false);
                node.addEventListener('mouseup', function() {
                    document.removeEventListener('mousemove', move, false);
                }, false);
            }

            function move(event) {
                var positionX = Number(node.getAttribute('x')) + event.clientX - startX;
                var positionY = Number(node.getAttribute('y')) + event.clientY - startY;
                node.setAttribute('x', positionX);
                node.setAttribute('y', positionY);
                startX = event.clientX;
                startY = event.clientY;
            }
        </script>
    </head>
    <body onload="setup();">
        <svg width="800" height="600">
            <rect width="800" height="600" fill="#444444"/>
            <rect id="node" x="368" y="268" width="64" height="64" rx="8" ry="8" fill="#222244"/>
        </svg>
    </body>
</html>

附注抱歉我的英语不好。

最佳答案

在鼠标按下的事件处理程序中,您必须调用preventDefault(),即

  node.addEventListener('mousedown', function(event) {
        event.preventDefault();
        document.addEventListener('mousemove', move, false);
        startX = event.clientX;
        startY = event.clientY;
    }, false);

这应该足够了,如果还不够,请尝试将 event.preventDefault() 调用添加到其他事件处理函数,即 mousemove 和 mouseup。

Firefox 对某些事件有默认处理程序,在这种情况下您不希望使用它们。

关于javascript - 在 Firefox 中移动 SVG 元素失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24009920/

相关文章:

javascript - .mov 文件在 Firebase 中存储为文本

javascript - document.createElement ('a' ).click() 在 Firefox 中不起作用

javascript - 是否可以在不使用 stroke 的情况下为 SVG 路径设置动画?

javascript - PDF 中的 anchor 标记在 firefox 和 safari 中不可点击

java - 使用 Batik 的文本元素的边界框值错误

javascript - 为什么我的 SVG 形状之间存在间隙?

javascript - 我将如何在 Javascript 中循环遍历一个数组,添加一个词,然后返回一个数组(不使用 map )?

javascript - AngularJS:更新数组后ng-repeat不刷新

javascript - WebGL 不适用于 Firefox

javascript - mouseclick 事件 JavaScript 在 Firefox 中不起作用