D3.js:使用元素位置定位工具提示,而不是鼠标位置?

Ric*_*ard 39 javascript tooltip d3.js

我正在使用D3绘制散点图.当用户将鼠标悬停在每个圆圈上时,我想显示工具提示.

我的问题是,我可以追加提示,但他们使用的鼠标事件定位成d3.event.pageXd3.event.pageY,所以他们不会在每个圆圈一贯定位.

相反,有些位于圆圈的左侧,有些位于右侧 - 这取决于用户的鼠标进入圆圈的方式.

这是我的代码:

circles
  .on("mouseover", function(d) {         
    tooltip.html(d)  
      .style("left", (d3.event.pageX) + "px")     
      .style("top", (d3.event.pageY - 28) + "px");    
  })                  
  .on("mouseout", function(d) {       
    tooltip.transition().duration(500).style("opacity", 0);   
  });
Run Code Online (Sandbox Code Playgroud)

并且是一个JSFiddle显示问题:http://jsfiddle.net/WLYUY/5/

有什么方法可以使用圆心的中心作为定位工具提示的位置,而不是鼠标位置?

Lar*_*off 30

在您的特定情况下,您可以简单地用于d定位工具提示,即

tooltip.html(d)  
  .style("left", d + "px")     
  .style("top", d + "px");
Run Code Online (Sandbox Code Playgroud)

为了使这更加通用,您可以选择被鼠标悬停的元素并获取其坐标来定位工具提示,即

tooltip.html(d)  
  .style("left", d3.select(this).attr("cx") + "px")     
  .style("top", d3.select(this).attr("cy") + "px");
Run Code Online (Sandbox Code Playgroud)

  • 谢谢 - 我害怕使用`d3.select(this).attr("cx")`只有在`<body>`和`<svg>`元素具有相同的定位时才有效.见http://jsfiddle.net/WLYUY/6/ (2认同)
  • 如果您有其他内容,则必须将SVG的偏移量添加到该位置,请参阅http://jsfiddle.net/WLYUY/7/ (2认同)
  • 我想出了这个: var matrix = this.getScreenCTM().translate(+this.getAttribute("cx"),+this.getAttribute("cy"));tip.style("left", ( window.pageXOffset + 矩阵.e) + "px").style("top", (window.pageYOffset + 矩阵.f + 30) + "px");&lt;/code&gt; (2认同)

Box*_*uan 15

找到了这里,可能解决你的问题,即使<body><svg>有不同的定位.这假设您absolute为工具提示设置了位置.

.on("mouseover", function(d) {
    var matrix = this.getScreenCTM()
        .translate(+ this.getAttribute("cx"), + this.getAttribute("cy"));
    tooltip.html(d)
        .style("left", (window.pageXOffset + matrix.e + 15) + "px")
        .style("top", (window.pageYOffset + matrix.f - 30) + "px");
})
Run Code Online (Sandbox Code Playgroud)


Jar*_*ber 6

根据我的经验,最简单的解决方案如下:

首先,getBoundingClientRect()获取元素的位置。

然后,使用window.pageYOffset调整相对于您所在位置的高度。

例如

.on('mouseover', function(d) {
    let pos = d3.select(this).node().getBoundingClientRect();
    d3.select('#tooltip')
        .style('left', `${pos['x']}px`)
        .style('top', `${(window.pageYOffset  + pos['y'] - 100)}px`);
})
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,我不使用 X 的偏移量,因为我们很少需要(除非您水平滚动)。

添加window.pageYOffsetpos['y']给我们当前的鼠标位置(无论我们在页面上的哪个位置)。我减去 100,将工具提示放置在其上方一点。