如何在可折叠树形图中的节点上鼠标悬停时显示节点名称

时间:2013-10-10 13:57:22

标签: d3.js

我正在开发可折叠树图。我试图在节点上生成鼠标悬停事件。 当我在节点上鼠标悬停时,它应该显示节点的名称。我试过,但我不知道如何计算转换属性值以显示节点上方或下方的名称。

var nodeEnter = node.enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
      .on("click", click)
      .on("mouseover", function(d){
            alert("over");
        d3.select(this).attr('transform', function(d){ return 'translate(?,?)'})
        .text(d.name + ": " + d.id)
        .style('display', null);
      })
      .on("mouseout", function(d){ alert("out"); d3.select(this).style('display', 'none'); });
  

翻译(?,?)

可折叠树图链接:http://bl.ocks.org/mbostock/4339083

请尽力帮助我 感谢

1 个答案:

答案 0 :(得分:14)

将类节点组转换为其位置,如果要在其下添加项,则可以使用相对坐标。例如,圆的中心(默认)位于相对于组的(0,0)坐标处。如果你想在圆圈下添加10 px的文本,在右边添加20 px,你应该这样做:

var nodeEnter = node.enter().append("g")
  .attr("class", "node")
  .attr("transform", function(d) { 
      return "translate(" + source.y0 + "," + source.x0 + ")"; 
  })
  .on("click", click)
  .on("mouseover", function(d) {
      var g = d3.select(this); // The node
      // The class is used to remove the additional text later
      var info = g.append('text')
         .classed('info', true)
         .attr('x', 20)
         .attr('y', 10)
         .text('More info');
  })
  .on("mouseout", function() {
      // Remove the info text on mouse out.
      d3.select(this).select('text.info').remove();
  });

问候。

相关问题