【问题标题】:Equivalent method of ".getComputedTextLength()" in d3.jsd3.js 中“.getComputedTextLength()”的等效方法
【发布时间】:2017-03-10 12:46:53
【问题描述】:

d3 中的.getComputedTextLength() 方法等价于什么。 .getComputedTextLength() 适用于 Dom 元素而不是 d3 元素的对象。
编辑(添加图片)

【问题讨论】:

    标签: javascript d3.js svg


    【解决方案1】:

    D3 选择实际上是对象(从 D3 v4.0 开始)。但是,没有计算对象中文本长度的方法,因为对象本身在 DOM 中不存在,因此没有长度。您只能计算 DOM 元素的长度(以像素为单位)。

    话虽如此,您可以将getComputedTextLength() 与 D3 选择一起使用,前提是您使用该选择指向 SVG 元素。例如,使用node():

    d3.select("foo");//this is a D3 selection
    d3.select("foo").node();//this is the DOM element
    

    这是一个演示:

    var svg = d3.select("svg");
    var text = svg.append("text")
    	.attr("x", 10)
    	.attr("y", 30)
    	.text("Hello world!");
    	
    console.log("the text has " + d3.select("text").node().getComputedTextLength() + " px")
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <svg></svg>

    【讨论】:

    • d3.select("foo").node(); 仍在返回 d3 对象(不是 DOM 元素)。我在销售人员工作
    • 不需要.select(),因为text中已经有了d3对象,所以text.node().getComputedTextLength()就是你所需要的。
    【解决方案2】:

    只需使用 this 访问选择操作中的 DOM 元素即可受益于使用 D3 进行的批量节点处理,例如

    d3.selectAll('tspan.myClass')
      .each(function(d) {
        console.log(this.getComputedTextLength());
      });
    

    d3.selectAll('tspan.myClass')
      .attr('transform', function(d) {
        var width = this.getComputedTextLength() + 2 * padding;
        return 'translate(' + width / 2 + ' 0)');
      });
    

    thisbound to the current DOM node

    selection.node() only returns 选择中的第一个元素。

    截至D3 4.* 还有selection.nodes() 在选择中恢复all DOM nodes,所以你可以这样做

    d3.selectAll('tspan.myClass').nodes().forEach(function(el) {
      console.log(el.getComputedTextLength());
    });
    

    虽然它的使用不如通过thisselection.attrselection.styleselection.filterselection.each 等中抓取元素,如上面的sn-ps。

    【讨论】:

      猜你喜欢
      • 2021-09-15
      • 1970-01-01
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      相关资源
      最近更新 更多