gpt4 book ai didi

javascript - 文本不会停留在 d3 树节点上

转载 作者:行者123 更新时间:2023-11-29 17:59:15 25 4
gpt4 key购买 nike

完整的 d3 新手在这里。我有我正在使用的这个 d3 树(这里是工作 jsfiddle https://jsfiddle.net/Joe123/vq4jpr1s/16/ )并且我有它以便每个节点的文本换行到节点的大小。但是,如您所见,在同一节点上多次单击后,文本会恢复为展开状态,我无法弄清楚原因。有人有什么想法吗?任何帮助将不胜感激。

这是包装函数:

    function wrap(text, width) {
text.each(function() {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1,
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 5).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 5).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
d3.select(this.parentNode.children[0]).attr("height", 20 * (lineNumber+1));


});
}

wrap(d3.selectAll('text'),150);

下面是点击函数,我尝试从这里调用 wrap 函数但没有成功。

function click(d) {

if (d.children) {
d._children = d.children;
d.children = null;

} else {
d.children = d._children;

}
update(d);
}

最佳答案

问题是,当您尝试基于空格进行拆分时(第二次以后),文本已经没有空格了。

所以而不是做

words = text.text().split(/\s+/).reverse(),

这样做

words = d3.select(this).data()[0].name.split(/\s+/).reverse(),

工作示例 here

关于javascript - 文本不会停留在 d3 树节点上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36344534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com