Collapse/expand child nodes of tree in d3.js?

*爱你&永不变心* 提交于 2019-12-01 02:32:18

问题


I'm building a tree structure (or rather modifying one of the examples with a set of my own data in my own json) and I'm trying to create some functionality:

My tree's layout is that from the tree example: http://mbostock.github.com/d3/ex/cluster.html

I am adding (to the circles) an onclick event which I would like to collapse the children of the clicked node. That is to say, when a user clicks the steelblue circle associated with a node, I want that nodes children to disappear.

I've scoured the documentation and I haven't turned up anything which would allow me to make nodes collapse or disappear.

What could I do?


回答1:


There's this:

http://mbostock.github.com/d3/talk/20111018/tree.html

There are a number of other interactive hierarchical layout examples from my SVG Open keynote.




回答2:


Unfortunately I'm still getting up to speed with D3, and am not sure how to best answer your question. But Here's a force-directed layout which allows you to show/hide nodes by clicking on them, which might give you some ideas: http://bl.ocks.org/1062288




回答3:


There's a couple approaches, one is just to use regular stying to hide the markup of the children (opacity: 0, or display: none). However, this just makes the data invisible, the tree maintains its shape as if the data is there, you just can't see it.

Usually you'll want the tree to pretend the data isn't there and update accordingly, for that you can use the same approach as the force-directed layout example in the above link.

It boils down to: 1) Use a function to build the d3 tree 2) append a click event to the collapsible nodes 3) The click event renames the children property of the node and calls the function in 1) which redraws the tree without that node's children.

Here's the relevant code from the link in nkoren's answer ( http://bl.ocks.org/1062288 ):

function update() { 
    // build the tree layout here
    //  append on("click", click) to the collapsible nodes
}

// Toggle children on click
function click(d) {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }
  update();
}


来源:https://stackoverflow.com/questions/9541511/collapse-expand-child-nodes-of-tree-in-d3-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!