javascript D3 的鼠标相对于父元素的坐标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18571563/
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-10-27 12:26:14  来源:igfitidea点击:

D3's mouse coordinates relative to parent element

javascriptd3.jsmousecoordinates

提问by Patryk

I would like to get mouse coordinates relative to parent or any other element in the DOM other than thisbut I keep getting

我想获取相对于父级或 DOM 中任何其他元素的鼠标坐标,this但我一直在获取

Uncaught TypeError: Object [object Array] has no method 'getBoundingClientRect' d3.v3.min.js:1
H d3.v3.min.js:1
vo.mouse d3.v3.min.js:3
(anonymous function) index.html:291
(anonymous function)

My code :

我的代码:

.on("mouseup", function(d){
    var th = d3.select( this );

    var coordinates = [0, 0];
    coordinates = d3.mouse( d3.select("body") );
    console.log( coordinates[1] );
    console.log( window );
    //th.attr("cy", d3.mouse),
    //d.newY = th.attr("cy");
    console.log(d);
});

As far as I have noticed I can only get mouse coordinates relative to element that I have attached .on("mouseup", ...)event listener.

据我所知,我只能获取相对于已附加.on("mouseup", ...)事件侦听器的元素的鼠标坐标。

Is there a way to get those coordinates relative to other element in the DOM ?

有没有办法获得这些坐标相对于 DOM 中的其他元素?

采纳答案by Tom Jorissen

You can use d3.event.pageX and d3.event.pageY. An example where I use this:

您可以使用 d3.event.pageX 和 d3.event.pageY。我使用它的一个例子:

.on("mouseover", function(d){
        hover.transition().duration(200).style("opacity", .9);
        hover.html(new Date(d.creationDate)+": "+d.reactionTime).style("left", d3.event.pageX+"px").style("top", (d3.event.pageY - 28)+"px");
    });

回答by

d3.mouseexpects a DOM element, not a d3 selection.

d3.mouse需要一个 DOM 元素,而不是 d3 选择。

d3.mouse(d3.select('body').node())

Of course selecting the body can be even easier:

当然,选择身体会更容易:

d3.mouse(document.body)

@Tom's answer works also in your case because you want the position relative to the page, but it doesn't work if you want the position relative to some other container.

@Tom 的答案也适用于您的情况,因为您想要相对于页面的位置,但如果您想要相对于其他容器的位置,则它不起作用。

Say you want to position a popup where the user clicked and you want to position it relative to the svg element so that it pans with the rest of your display.

假设您想在用户单击的位置定位一个弹出窗口,并且您想相对于 svg 元素定位它,以便它与显示的其余部分一起平移。

nodeEnter.on('click', function(d){
  var coordinates = d3.mouse(svg.node());
});