【问题标题】:Displaying text over a node in a d3 force-layout graph在 d3 强制布局图中的节点上显示文本
【发布时间】:2014-06-25 04:19:53
【问题描述】:

我正在使用 d3 创建一个强制布局图,并且当我将鼠标悬停在该节点上时,我试图使特定节点的名称出现。我知道如何在任何鼠标悬停效果之前添加文本,并认为我可以将那部分代码移动到鼠标悬停函数中,但这不起作用。当我将鼠标移出节点时,我还需要使文本消失。这是我尝试将名称添加到节点的鼠标悬停功能:

function mouseover() {
    d3.select(this).transition()
         .duration(750)
         .attr("r", function(d) {return d.size + 10;});
    var labels = gnodes.append("text")
         .text(function(d) { return d.name;})
         console.log(labels);
                    }

这里也是完整代码的链接:

http://jsfiddle.net/ohiobucks23/QvVU6/

【问题讨论】:

  • 使用 D3 技巧库,因为它看起来不错且易于集成
  • 感谢您的建议。我会考虑在未来添加工具提示,因为我的目标是让它成为一个向下钻取的图表。

标签: javascript d3.js onmouseover force-layout


【解决方案1】:

如果不使用 Bhatt 推荐的工具提示,您需要:

1) 在drawGraph() 函数之外声明gnodes 以便鼠标函数可见,并且

2) 对鼠标功能进行如下修改:

function mouseover(d) {
   d3.select(this).transition()
       .duration(750)
       .attr("r", function (d) {return d.size + 10;});

   // locate node and append text; add class to facilitate subsequent deletion
   gnodes.filter(function (o) {return o.index === d.index;})
       .append("text")
       .attr("class", "nodetext")
       .text(d.name);
}

function mouseout(d) {
   d3.select(this).transition()
       .duration(750)
       .attr("r", function (d) {return d.size;});

   // delete text based on class
   d3.selectAll(".nodetext").remove();
}

这是完整的FIDDLE。我更改了根节点元素的文本,以便您可以看到mouseover 函数确实作用于所选节点。

【讨论】:

  • 太棒了!谢谢!没有考虑在那里使用 gnodes。
猜你喜欢
  • 1970-01-01
  • 2014-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-15
  • 1970-01-01
  • 2014-06-30
  • 2016-05-17
相关资源
最近更新 更多