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>
只需使用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.attr
、selection.style
、selection.filter
、selection.each
等中,通过this
获取元素的用法更符合惯用语,但在上述片段中,使用d3.select
也是可行的。如果我理解正确的话,OP想要一个类似于D3.js中getComputedTextLength
函数的功能,但不使用D3.js。
在普通的Javascript中没有这样的方法。然而,如果元素是SVG元素,你可以使用getBBox()
来检索元素适合的最小矩形的坐标和尺寸。
如果元素不属于SVG,则使用getClientRect()
或getBoundingClientRect()
。
node.getBoundingClientRect().width
不是代码吗?
我认为这个问题的答案就是这一行代码。对于这种情况有什么建议吗? - Leslie Wunode()
来选择作为常规DOM元素)。包括代码片段。
实际上,你的示例截图也证明了,只要从D3对象获取原生节点,getComputedTextLength()
就能正常工作。
事实上,提问者的描述还应该包括一个正确的代码示例。
由于我的评论可能引起其他Stack Overflow用户对你的回答进行负评,我已经点赞给你一个机会来修改你的回答。 - herrstrietzel
d3.select("foo").node();
仍然返回d3
对象(而非 DOM 元素)。我正在 Salesforce 中工作。 - ozil.select()
,因为您已经在text
中拥有了 d3 对象,所以text.node().getComputedTextLength()
就足够了。 - David R.