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

前端 未结 3 1562
花落未央
花落未央 2021-01-12 05:58

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 tr

相关标签:
3条回答
  • 2021-01-12 06:20

    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.

    0 讨论(0)
  • 2021-01-12 06:23

    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

    0 讨论(0)
  • 2021-01-12 06:44

    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();
    }
    
    0 讨论(0)
提交回复
热议问题