在下面的代码中,我试图在屏幕上一个接一个地插入 3 个字符串
为此,我需要计算已显示的标签的屏幕宽度,如 attr("x",...)
行中突出显示的那样。
如何在 d3 中的选择过程中引用前面的元素?
引用文献:How to refer to the previous element , how to calculate width of text before displaying it
var labels = ['a label', 'another label', 'a third label']
var textItems = svg.append('g')
.selectAll('.my_labels_text')
.data(labels)
.enter()
.append("text")
.attr("class", "my_labels_text")
.attr("text-anchor", "left")
.attr("x", function (d, i) { return <cumulated width of labels previously displayed>})
.attr("y", 10) // arbitrary y value
.text(function(d) { return d })
最佳答案
如果您需要保持运行宽度计数;只需在外部范围内使用一个变量:
<!DOCTYPE html>
<html>
<head>
<script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
</head>
<body>
<script>
var labels = ['a label', 'another label', 'a third label'];
var svg = d3.select('body')
.append('svg')
.attr('width', 1000)
.attr('height', 500);
var runningWidth = 10;
var textItems = svg.append('g')
.selectAll('.my_labels_text')
.data(labels)
.enter()
.append("text")
.attr("class", "my_labels_text")
.attr("text-anchor", "left")
.text(function(d) { return d })
.attr("y", 10) // arbitrary y value
.attr("x", function (d, i) {
var thisWidth = this.getComputedTextLength(),
rV = runningWidth;
runningWidth += thisWidth;
return rV;
});
</script>
</body>
</html>
关于javascript - D3 - 如何在文本选择中获取前一个元素的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37499983/