我正在尝试在 D3 中创建某些内容后更改其整个框架的宽度,具体取决于其中某些文本的宽度(这样它就不会被切断)。但是,我无法返回文本元素的宽度。
主体看起来像这样:
this.body = d3.select("#" + this.placeholderName)
.append("svg:svg")
.attr("class", "gauge")
.attr("width", this.config.size)
.attr("height", this.config.size + 150);
正文中的文本如下所示:
this.body.append("svg:text")
.attr("x", this.config.cx - 60)
.attr("y", this.config.cy / 2 + fontSize / 2)
.attr("dy", fontSize / 2)
.attr("text-anchor", "start")
.text(this.config.label)
.style("font-size", fontSize + "px")
.style("fill", "#333")
.style("stroke-width", "0px")
最后,我用这个改变了框架的宽度。我需要在此处输入什么作为第二个参数?
this.body.attr("width", <WIDTH OF TEXT ABOVE>);
谢谢
最佳答案
首先,当您创建文本元素时,为其指定一个类或 ID,以便稍后轻松选择它。
假设您给它 .attr('class', 'bodyText')
。
然后你可以使用 SVGTextContentElement.getComputedTextLength()
得到它的长度
您可以通过使用 selection.node()
从 d3 选择中获取实际的文本元素,然后在节点上调用该方法来为您的文本节点获取此值。像这样:
var textLength = d3.select('.bodyText').node().getComputedTextLength();
然后您可以在设置宽度属性时使用此值。
关于javascript - D3 根据对象的子项更改对象的宽度属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24959867/