我在 SVG 中的 g 元素内有一个圆圈。 g 元素可以简单地根据 x 坐标移动。 g 元素的位置可以随着其移动而改变。圆也会像在 g 元素中那样移动。我的问题是如何检索该圆圈在 SVG 中的位置而不是其在 g 元素中的位置?我尝试了以下代码,但无法得到我所期望的:circleGroup.on("mouseover", function()
{
var 翻译 = d3.transform(d3.select(this).attr("transform")).translate;
警报(翻译[0].x);
});
有人可以帮我检索 SVG 中圆的位置而不是 g 元素中的位置吗?我需要获取圆的位置,以便从其在 SVG 中的位置(而不是圆所在的 g 元素)开始绘制一条线。非常感谢您的帮助。这里是:JsFiddle
最佳答案
如果您想要鼠标悬停的圆圈的位置,我会在圆圈上创建我的 .on
处理程序,而不是 g
元素(这样您就知道哪个元素接收到事件):
...
var circles = circleGroup.selectAll("circle")
.data(circleData)
.enter()
.append("circle")
.on("mouseover", mouseover)
...
function mouseover() {
var self = d3.select(this);
alert(self.attr('cx'));
}
已更新fiddle .
编辑评论
哎呀,错过了转换。怎么样:
function mouseover()
{
var self = d3.select(this);
var translate = d3.transform(self.attr("transform")).translate;
alert(+self.attr('cx') + translate[0]);
}
已更新fiddle 2 .
关于javascript - 如何使用 D3.js 获取 SVG 中 g 元素中的圆位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29633075/