在d3.js中与".getComputedTextLength()"等价的方法是什么?

7
在d3中,相当于.getComputedTextLength()方法的是什么?.getComputedTextLength()方法作用于Dom元素而不是d3元素对象。
编辑(添加图片)
enter image description here
4个回答

14

D3选择集实际上是对象(自D3 v4.0以来)。然而,由于对象本身在DOM中不存在,因此没有一种方法可以计算对象中文本的长度,因此对象本身也没有长度。您只能计算DOM元素的长度(以像素为单位)。

话虽如此,如果您使用D3选择集指向SVG元素,您可以使用getComputedTextLength()计算D3选择集的长度。例如,使用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 元素)。我正在 Salesforce 中工作。 - ozil
2
不需要执行 .select(),因为您已经在 text 中拥有了 d3 对象,所以 text.node().getComputedTextLength() 就足够了。 - David R.

4

只需使用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)');
  });

this绑定到当前DOM节点

selection.node() 仅返回选择集中的第一个元素。

D3 4.*开始,还有selection.nodes()可以恢复选择集中所有DOM节点,因此您可以执行以下操作:

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

虽然在selection.attrselection.styleselection.filterselection.each等中,通过this获取元素的用法更符合惯用语,但在上述片段中,使用d3.select也是可行的。

0

如果我理解正确的话,OP想要一个类似于D3.js中getComputedTextLength函数的功能,但不使用D3.js。

在普通的Javascript中没有这样的方法。然而,如果元素是SVG元素,你可以使用getBBox()来检索元素适合的最小矩形的坐标和尺寸。

如果元素不属于SVG,则使用getClientRect()getBoundingClientRect()


0

它的 node.getBoundingClientRect().width

在我的情况下,this 是一个 d3 对象。所以你可以使用 getComputedTextLength() 来获取对象的宽度。

如果你正在使用纯 JavaScript,你可以使用 node.getBoundingClientRect().width

enter image description here


enter image description here


请将代码示例以文本形式发布。因此,请优先使用代码块或片段。截图应仅用作附加信息。 - herrstrietzel
@herrstrietzel 你的意思是 node.getBoundingClientRect().width 不是代码吗? 我认为这个问题的答案就是这一行代码。对于这种情况有什么建议吗? - Leslie Wu
参考@Gerardo Furtado的回答: 解释问题(D3对象需要上下文(each/this)或D3方法如node()来选择作为常规DOM元素)。包括代码片段。 实际上,你的示例截图也证明了,只要从D3对象获取原生节点,getComputedTextLength()就能正常工作。 事实上,提问者的描述还应该包括一个正确的代码示例。 由于我的评论可能引起其他Stack Overflow用户对你的回答进行负评,我已经点赞给你一个机会来修改你的回答。 - herrstrietzel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接