D3.js:使用元素位置而不是鼠标位置定位工具提示? [英] D3.js: Position tooltips using element position, not mouse position?

查看:2350
本文介绍了D3.js:使用元素位置而不是鼠标位置定位工具提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用D3绘制散点图。我想显示工具提示时,用户鼠标在每个圆圈。

I'm using D3 to draw a scatter graph. I would like to show tooltips when the user mouses over each circle.

我的问题是我可以附加工具提示,但它们使用鼠标事件 d3.event.pageX d3.event.pageY ,因此它们在每个圆圈上的位置不一致。

My problem is that I can append tooltips, but they're positioned using the mouse event d3.event.pageX and d3.event.pageY, so they are not positioned consistently over each circle.

相反,有些是略微在圆圈的左边,有些在右边 - 这取决于用户的鼠标如何进入圆圈。

Instead, some are slightly to the left of the circle, some to the right - it depends on how the user's mouse enters the circle.

这是我的代码:

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);   
  });

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

And is a JSFiddle showing the problem: http://jsfiddle.net/WLYUY/5/

有什么方法可以使用圆心本身

Is there some way I can use the centre of the circle itself as the position to orient the tooltip, not the mouse position?

推荐答案

在您的特定情况下,您可以简单地使用<$ c $作为定位工具提示的位置,而不是鼠标位置? c> d 以定位工具提示,即

In your particular case you can simply use d to position the tooltip, i.e.

tooltip.html(d)  
  .style("left", d + "px")     
  .style("top", d + "px");

为了使这一点更加一般,你可以选择被鼠标悬停的元素,坐标定位工具提示,即

To make this a bit more general, you can select the element that is being moused over and get its coordinates to position the tooltip, i.e.

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

这篇关于D3.js:使用元素位置而不是鼠标位置定位工具提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆