【发布时间】:2017-03-10 12:46:53
【问题描述】:
【问题讨论】:
标签: javascript d3.js svg
【问题讨论】:
标签: javascript d3.js svg
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()就是你所需要的。
只需使用 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 是bound 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());
});
虽然它的使用不如通过this 在selection.attr、selection.style、selection.filter、selection.each 等中抓取元素,如上面的sn-ps。
【讨论】: