D3 工具提示不跟随鼠标
D3 tooltip not following the mouse
我使用 D3 和面向对象编程创建了一个包含多个图表的网页。
工作代码link--> https://codepen.io/mohan-ys/pen/LYLwqrK
我面临的问题是工具提示不在鼠标位置,它在其他地方。
我尝试使用 d3.event.pageX
& d3.event.pageY
而不是上面代码中的 vis.mouse[0]
& vis.mouse[1]
但它不起作用。
我收到如图所示的工具提示。当鼠标在图表的右端时,工具提示会进一步向右移动,它会在中间某处靠近,当光标在图表的左端时它会移动到另一边!
页面被调整大小,那就是完全不同的行为了!
任何人都可以帮助使所有图表的鼠标指针(鼠标指针的左上角)的工具提示正确,甚至在调整页面大小时(图表随页面大小调整而缩放)。
垂直线完美地跟随鼠标!因此,如果有另一种创建工具提示的方法而不是 div
,那对我来说也可以。
根本问题已解决 but the answer doesn't directly solve your problem. Basically, there's a second and optional argument to d3.pointer
称为 target
这样:
If target is not specified, it defaults to the source event’s
currentTarget property, if available. If the target is an SVG element,
the event’s coordinates are transformed using the inverse of the
screen coordinate transformation matrix...
您可以使用下面的这个参数,注意如果您尝试更新 vis.mouse
:
,它会破坏您的垂直跟踪线
// mouse moving over canvas
vis.mouse = d3.pointer(event); // keep this for the vertical tracking line
vis.mouse2 = d3.pointer(event, d3.select(vis.chartLocation)); // <--- NEW VARIABLE!
现在 vis.mouse2
有一个相对的 x
和 y
- 所以在设置 div
的 style
的地方使用它们:
d3
.select(vis.chartLocation)
.selectAll("#tooltip")
.html((d, i) => {
vis.xDate = d.values[vis.idx - 1].date;
return vis.xDate.toLocaleDateString("pt-PT");
})
.style("display", "block")
.style("left", vis.mouse2[0] + "px") // use vis.mouse2
.style("top", vis.mouse2[1] + "px") // use vis.mouse2
线索在于您的第一个选择是 vis.chartLocation
。
我使用 D3 和面向对象编程创建了一个包含多个图表的网页。
工作代码link--> https://codepen.io/mohan-ys/pen/LYLwqrK
我面临的问题是工具提示不在鼠标位置,它在其他地方。
我尝试使用 d3.event.pageX
& d3.event.pageY
而不是上面代码中的 vis.mouse[0]
& vis.mouse[1]
但它不起作用。
我收到如图所示的工具提示。当鼠标在图表的右端时,工具提示会进一步向右移动,它会在中间某处靠近,当光标在图表的左端时它会移动到另一边!
页面被调整大小,那就是完全不同的行为了!
任何人都可以帮助使所有图表的鼠标指针(鼠标指针的左上角)的工具提示正确,甚至在调整页面大小时(图表随页面大小调整而缩放)。
垂直线完美地跟随鼠标!因此,如果有另一种创建工具提示的方法而不是 div
,那对我来说也可以。
根本问题已解决 d3.pointer
称为 target
这样:
If target is not specified, it defaults to the source event’s currentTarget property, if available. If the target is an SVG element, the event’s coordinates are transformed using the inverse of the screen coordinate transformation matrix...
您可以使用下面的这个参数,注意如果您尝试更新 vis.mouse
:
// mouse moving over canvas
vis.mouse = d3.pointer(event); // keep this for the vertical tracking line
vis.mouse2 = d3.pointer(event, d3.select(vis.chartLocation)); // <--- NEW VARIABLE!
现在 vis.mouse2
有一个相对的 x
和 y
- 所以在设置 div
的 style
的地方使用它们:
d3
.select(vis.chartLocation)
.selectAll("#tooltip")
.html((d, i) => {
vis.xDate = d.values[vis.idx - 1].date;
return vis.xDate.toLocaleDateString("pt-PT");
})
.style("display", "block")
.style("left", vis.mouse2[0] + "px") // use vis.mouse2
.style("top", vis.mouse2[1] + "px") // use vis.mouse2
线索在于您的第一个选择是 vis.chartLocation
。