D3 - 如何在文本选择中获取先前元素的宽度

时间:2016-05-28 14:09:21

标签: javascript d3.js

在下面的代码中,我试图在屏幕上插入3个字符串,一个在另一个

旁边

为此,我需要计算已经显示的标签的屏幕宽度,如attr("x",...)行中突出显示的那样。

如何在d3中选择前参考前面的元素?

参考文献:How to refer to the previous elementhow to calculate width of text before displaying it

var labels = ['a label', 'another label', 'a third label']

var textItems = svg.append('g')
    .selectAll('.my_labels_text')
    .data(labels)
    .enter()
    .append("text")
    .attr("class", "my_labels_text")
    .attr("text-anchor", "left")
    .attr("x", function (d, i)   { return <cumulated width of labels previously displayed>})
    .attr("y", 10) // arbitrary y value
    .text(function(d) { return d })

1 个答案:

答案 0 :(得分:2)

如果您需要保持运行宽度计数;只需在外部范围内使用变量:

&#13;
&#13;
<!DOCTYPE html>
<html>

  <head>
    <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
  </head>

  <body>
    <script>
      var labels = ['a label', 'another label', 'a third label'];
      
      var svg = d3.select('body')
        .append('svg')
        .attr('width', 1000)
        .attr('height', 500);

      var runningWidth = 10;
      var textItems = svg.append('g')
          .selectAll('.my_labels_text')
          .data(labels)
          .enter()
          .append("text")
          .attr("class", "my_labels_text")
          .attr("text-anchor", "left")
          .text(function(d) { return d })
          .attr("y", 10) // arbitrary y value
          .attr("x", function (d, i)   { 
            var thisWidth = this.getComputedTextLength(),
                rV = runningWidth;
            runningWidth += thisWidth;
            return rV;
          });
      
    </script>
  </body>

</html>
&#13;
&#13;
&#13;