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

早过忘川 提交于 2019-12-01 04:35:49

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.

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

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