展开一个节点时折叠其他节点

展开一个节点时折叠其他节点

本文介绍了d3.js树布局:展开一个节点时折叠其他节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用d3.js的树布局()中,



例如,在上面的演示中,尝试以下操作:


  1. 点击家长1(显示儿童1和儿童2)

  2. 1.1)

  3. 点击儿童2(显示儿童2.1)

现在你应该看到孩子1和孩子2的孩子。



我想要发生以下情况:


  1. 点击家长1(显示儿童1和儿童2)




  2. 点击 b
    $ b

    因此,除了活动分支之外的节点的子节点应该被隐藏。



    (当然,我将使用一个相当大的数据集)

    解决方案

    一个简单的解决方案是修改点击功能如果节点具有父节点,则父节点的子节点都将被折叠,但是只有当子节点不是被点击的节点时。

      function click(d){
    if(d.children){
    d._children = d.children;
    d.children = null;
    } else {
    d.children = d._children;
    d._children = null;
    }
    //如果节点有父节点,则折叠它的子节点
    //除了此被点击的节点。
    if(d.parent){
    d.parent.children.forEach(function(element){
    if(d!== element){
    collapse
    }
    });
    }
    update(d);
    }

    更新jsbin:


    On a tree layout using d3.js (example), I'd like to collapse nodes that are not in the branch that has been clicked on.

    For example, in the above demo, try the following:

    1. click on "Parent 1" (Child 1 and Child 2 are shown)
    2. click on "Child 1" (Child 1.1 is shown)
    3. click on "Child 2" (Child 2.1 is shown)

    Now you should see both the children of "Child 1" and "Child 2".

    I would like to have the following happen:

    1. click on "Parent 1" (Child 1 and Child 2 are shown)
    2. click on "Child 1" (Child 1.1 is shown)
    3. click on "Child 2" (Child 2.1 is shown, Child 1.1 is hidden)

    So children of nodes other than on the "active" branch should be hidden.

    How can I best approach this? (efficiently of course, as I'll be using a fairly large dataset)

    解决方案

    One simple solution is to modify the click function such that if the node has a parent, the parent's children are each collapsed, but only if the child isn't the node that was clicked on.

    function click(d) {
      if (d.children) {
        d._children = d.children;
        d.children = null;
      } else {
        d.children = d._children;
        d._children = null;
      }
      // If the node has a parent, then collapse its child nodes
      // except for this clicked node.
      if (d.parent) {
        d.parent.children.forEach(function(element) {
          if (d !== element) {
            collapse(element);
          }
        });
      }
      update(d);
    }
    

    Updated jsbin: http://jsbin.com/etIJABU/2/edit

    这篇关于d3.js树布局:展开一个节点时折叠其他节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 06:53