如何在 d3 强制定向布局节点上显示工具提示?

How to show the tooltip on d3 force directed layout node?

我已经构建了一个带有层次结构数据的示例 d3 可视化,它非常有效 well.I 当用户在节点上移动鼠标时需要显示绑定到 icon/node 的数据。我也这样做了,效果很好。

我需要根据工具提示上的节点显示数据。我不想为此绑定 html 元素。

这是我的代码

HTML:

  <div id="chart"></div>

JS:

 node = vis.selectAll(".node");
        node = node.data(force.nodes());
        node.exit().remove();
        node.enter().append("g")
            .attr("class", "node")
            .on("click", click).on("mouseover", function(){return tooltip.style("visibility", "visible") 
                 tooltip.text
                 ;})
.on("mousemove", function(){return tooltip.style("top",
    (d3.event.pageY - 130)+"px").style("left",(d3.event.pageX - 130 )+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");});

APPLICATION ON FIDDLE

要将 class 添加到工具提示,请执行以下操作:

var tooltip = d3.select("#chart")
        .append("div")
        .attr("class", "my-tooltip")//add the tooltip class
        .style("position", "absolute")
        .style("z-index", "10")
        .style("visibility", "hidden");
    tooltip.append("div")
        .attr("id", "tt-name")
        .text("simple");
    tooltip.append("div")
        .attr("id", "tt-size")
        .text("simple");

要在鼠标悬停时添加值和大小,请执行以下操作:

tooltip.select("#tt-name").text(d.name)
tooltip.select("#tt-size").text(d.size)

更新后的代码是 here: