使用d3和d3.tip计算div元素的坐标



我希望使用d3-tip的工具提示动态地放置在我用以下代码编写的文本旁边:

在Javascript 中

$(".intro h2").html("Nextbus prediction of " + "<font size=5>" + cutoff + "</font>" + "minutes really means:")
.on('mouseover', tip2.show)
.on('mouseout', tip2.hide);

在HTML中。。。

<div class="intro">
    <span class="underline"><h2></h2></span>
</div>

当我用style("left", 300+"px") 这样定义工具提示时,我可以让它出现在一个绝对的位置

 var tip2 = d3.tip()
        .attr('class', 'd3-tip')
        .direction("s")
        .html(function(d) {
            return "this my text for the hover over of the sentence!"
        })
        .style("left", 300+"px")
        .style("top", 150+"px")

但当我取出style("left", 300+"px")时,无论我如何破解它,文本都会放在图的左下角offset.

我想用一个可以检索到我用鼠标悬停在div上的坐标的东西来代替300。

这是我的小提琴:http://jsfiddle.net/0yfbhtcv/1/(永远不要忘记没有出现的情节……这只是在从我的代码到jsfiddle的翻译中丢失的,对于这个问题来说不应该是必要的)

这不使用d3.tip,但我认为它可以用普通的ol d3实现您想要的功能,它制作了一个div,您可以将HTML或文本放入其中,并在鼠标所在的位置弹出:

var div = d3.select("body").append("div")   // put the tooltip in a separate div
      .attr("class", "tooltip");

然后

d3.selectAll(".your_class")
    .on("mouseover", function (d) {
      div.transition()
        .duration(200)
        .style("opacity", 0.9);
     div.html( d.whatever + <somehtml> + "etc")
        .style("left", (d3.event.pageX) + "px")     
        .style("top", (d3.event.pageY - 28) + "px"); })
    .on("mouseout", function (d) {
      div.transition()
        .duration(300)
        .style("opacity", 0)
    });

最新更新