javascript - 如何使用 offsetX 和 offsetY 在 firefox 浏览器中的 svg 内移动一个圆圈?

标签 javascript firefox cross-browser

我用 javascript 编写了一些代码,允许用户在 svg 中操作圆圈。

我在下面提供了一些代码。在这里你可以移动一个圆圈。在 Chrome 和 Egde 上它都能完美运行。在 Firefox 上它不起作用。当我移动圆圈时,它几乎每隔一个像素就会传送到左上角。我的版本是 67.0.4。

以下代码使用 html 文件中 ID 为“svg”的 svg。

Codepen Example

const svg = document.getElementById('svg');
const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", "100px");
circle.setAttribute("cy", "100px");
circle.setAttribute("r", "50px");
circle.setAttribute("fill", "blue");
svg.appendChild(circle);

let pressed = false;

svg.addEventListener("mousedown", (e) => {
  pressed = true;
});

svg.addEventListener("mousemove", (e) => {
  if (pressed) {
    circle.setAttribute("cx", e.offsetX);
    circle.setAttribute("cy", e.offsetY);
  }
});

svg.addEventListener("mouseup", (e) => {
  pressed = false;
});

最佳答案

使用 clientXclientY 。我认为 offsetXoffsetY 在 Firefox 中已弃用

const svg = document.getElementById('svg');
const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", "100px");
circle.setAttribute("cy", "100px");
circle.setAttribute("r", "50px");
circle.setAttribute("fill", "blue");
svg.appendChild(circle);

let pressed = false;

svg.addEventListener("mousedown", (e) => {
  pressed = true;
});

svg.addEventListener("mousemove", (e) => {
  if (pressed) {
    circle.setAttribute("cx", e.clientX);
    circle.setAttribute("cy", e.clientY);
  }
});

svg.addEventListener("mouseup", (e) => {
  pressed = false;
});
svg {
  background: grey;
}
<svg id="svg" width="300" height="200"><svg>

关于javascript - 如何使用 offsetX 和 offsetY 在 firefox 浏览器中的 svg 内移动一个圆圈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56954246/

相关文章:

jquery - 在 IE9 和 Opera 中显示标题

javascript - Sails.js 使用回调中的值设置模型值

javascript - document.onmouseover 和 onmouseout 事件参数在 IE 8 和 IE7 中未定义

html - 浏览器什么时候添加 CSS 样式作为属性,即使这些没有明确指定?

javascript - 当可滚动框位于具有不透明度和高度的元素顶部时,Firefox 不会重新绘制

css - PC 和 Mac 之间的 css 渲染不一致

javascript - TypeScript angularjs 事件绑定(bind)

javascript - Next.js 页面中的 ag-grid 渲染

macos - 这是 Mac OS 上 Firefox 扩展的已知问题吗?

jquery - 相同的源代码 - 不同的浏览器 - jQuery 插件适用于 Firefox 和 Chrome,不适用于 IE 9