Javascript d3 点击坐标相对于页面而不是 svg - 如何翻译它们(Chrome 错误)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10247209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:28:38  来源:igfitidea点击:

d3 click coordinates are relative to page not svg - how to translate them (Chrome error)

javascriptgoogle-chromesvgclickd3.js

提问by ballaw

When an event is in play, d3.event.x gives the position of the x coordinate of the mouse click, but relative to the entire HTML doc. I tried using jQuery's $('svg').position() to get the actual position of the svg but this return blatantly fallacious values.

当事件发生时, d3.event.x 给出鼠标单击的 x 坐标的位置,但相对于整个 HTML 文档。我尝试使用 jQuery 的 $('svg').position() 来获取 svg 的实际位置,但这返回明显错误的值。

Is there some easy way to find the position of an svg relative to the page that I am overlooking? I am using Chrome, by the way, in case the jQuery problem is an obscure browser error.

有什么简单的方法可以找到 svg 相对于我正在俯瞰的页面的位置吗?顺便说一下,我正在使用 Chrome,以防 jQuery 问题是一个模糊的浏览器错误。

EDIT: I checked this in firefox and $('svg').position() returns the correct coordinates. ?!?

编辑:我在 Firefox 中检查了这个, $('svg').position() 返回正确的坐标。?!?

回答by mbostock

Instead of using d3.event, which is the browser's native event, use d3.mouseto get the coordinates relative to some container. For example:

而不是使用d3.event,这是浏览器的本机事件,而是使用d3.mouse来获取相对于某个容器的坐标。例如:

var svg = d3.select("body").append("svg")
    .attr("width", 960)
    .attr("height", 500);

var rect = svg.append("rect")
    .attr("width", "100%")
    .attr("height", "100%")
    .on("mousemove", mousemove);

function mousemove(d, i) {
  console.log(d3.mouse(this));
}