在不重构过多代码的情况下,只需更改
哪里
你在附加矩形。在这种情况下,文本本身的父节点:
node.select<SVGTSpanElement>("text")
.each(function(x, i) {
console.log(this.getComputedTextLength());
d3.select(this.parentNode).append("rect")
.attr("fill", "#cccccc05")
.attr("width", this.getComputedTextLength())
.attr("height", 20)
});
然而,最惯用的方法是
each()
对于
node
选择,不用于选择其中的文本。然后,你得到每个的文本长度
结点
元素,类似于:
node.each(function(x, i) {
d3.select(this).append("rect")
.attr("fill", "#cccccc05")
.attr("width", d3.select(this).select("text").node().getComputedTextLength())
.attr("height", 20)
});