[英]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.