javascript - D3 工具提示不跟随鼠标

标签 javascript d3.js

我使用 D3 和面向对象编程创建了一个包含多个图表的网页。

工作代码链接--> https://codepen.io/mohan-ys/pen/LYLwqrK

我面临的问题是工具提示不在鼠标位置,而是在其他地方。 我尝试使用 d3.event.pageXd3.event.pageY 而不是 vis.mouse[0]vis.mouse [1] 位于上面的代码中,但不起作用。

我得到如图所示的工具提示。当鼠标位于图表右端时,工具提示会进一步向右移动,靠近中间某处,当光标位于图表左端时,工具提示会移至另一侧!

页面大小被调整,那么这是一个完全不同的行为!

任何人都可以帮助让所有图表的工具提示位于鼠标指针右侧(鼠标指针的左上角),甚至在页面大小调整时(图表随页面大小调整而缩放)。

垂直线完美地跟随鼠标!因此,如果有另一种方法来创建工具提示而不是 div,这对我来说也可以。

enter image description here enter image description here enter image description here

最佳答案

根本问题已得到解决 here但答案并不能直接解决你的问题。基本上, d3.pointer 有第二个可选参数。称为目标,这样:

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 有一个相对的 xy - 所以在设置 style 的地方使用它们div 的:

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

关于javascript - D3 工具提示不跟随鼠标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69481490/

相关文章:

javascript - Angularjs变量在 Controller 中获取http不可见

javascript - 打印数组javascript中重复数字的索引

javascript - c3.js 中具有多个 XY 折线图的大量或未知数量的数据数组

javascript - 从带线的数据转换日期和时间

javascript - 显示图表

javascript - 光滑的轮播滚动

javascript - 在 ie (SVG) 上隐藏未找到图像的图标

javascript - d3.js:axisBottom 出现在顶部

javascript - jQuery |无法获取事件选项卡的 href

javascript - 使用 d3.js 的六 Angular 网格