[英]How can I get a list of tree-ancestors and tree-descendants from this d3.js layout.tree?
我正在试验和修改d3.js的这个例子来绘制一个基于JSON树结构的树。 这是树的一部分开头:
我正在尝试进行两次单独的修改,但我不知道如何做到这些:
my-old-class
和my-new-class
班之间切换他们的风格my-new-class
。 my-old-class
和my-new-class
班之间切换他们的风格my-new-class
。 我该怎么做?
除了我需要在nodeEnter.append("text")
语句中添加一个on-click函数之外,我根本不知道如何做#1。 但是这个功能应该做什么?
对于#2,我知道这是我需要修改的代码的相关部分。 像这样的东西:
nodeEnter.append("text")
.attr("x", function(d) { return d.children || d._children ? -10 : 10; })
.attr("dy", ".35em")
.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
.text(function(d) { return d.name; })
.style("fill-opacity", 1e-6)
.on("click", function(d) {
for (var currentAncestor = this.parentNode; /* WHAT EXPRESSION GOES HERE?? */; currentAncestor = currentAncestor.parentNode) {
var ancestorText = /* WHAT EXPRESSION GOES HERE?? */;
ancestorText.classed("my-new-class", !ancestorText.classed("my-new-class"));
ancestorText.classed("my-old-class", !ancestorText.classed("my-old-class"));
});
但我不知道要放什么东西来代替这两个表达式这样的,我通过正确的文本元素只有树的祖先循环(而不是DOM的祖先!)
编辑:
例如,在下面的屏幕截图中,当用户点击文本“data”时,我想要它的祖先文本(“vis”和“flare”)及其后代文本(出现在“data”右侧的每个单词)变成红色)
每个节点都应该有这样的父节点:
function collapse(d) {
if (d.children) {
d.children.forEach(function(child){
child.parent = d;//so now each node will have a parent except root node.
});
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
接下来是设置颜色的功能。 此函数将遍历给定节点并将其子项设置为具有颜色字段。
function setColor(d, color) {
d.color= color;
if (d.children) {
d.children.forEach(function(d){setColor(d,color)});
} else if(d._children){
d._children.forEach(function(d){setColor(d,color)});
}
}
在文本上单击调用此函数:
function textClick(d) {
setColor(root, "black");//set all the nodes to have black.
d1 = d;
//iterate over all its parent and make it red
while(d1){
d1.color = "red";
d1 = d1.parent;
}
//set color of the children node to red.
setColor(d, "red")
update(root);//call update so that the node text color is colored accordingly.
}
在这里工作代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.