【问题标题】:D3 hierarchy collapse to first level by defaultD3 层次结构默认折叠到第一级
【发布时间】:2020-09-30 06:41:56
【问题描述】:

我有下面的缩进树代码。我想默认折叠树并且只显示第一级子节点或根节点,没关系。我尝试了几种我认为不会成功的方法,我认为下面的当前部分可以解决问题:

function toggleAll(d) {
                   if (d.children) {
                   d.children.forEach(toggleAll);
                  toggle(d);
                   }
               }

                 root.children.forEach(toggleAll);
                  toggle(root);
                  });

下面是对应的flare.json文件的html:

<meta charset="utf-8">
<style>

.node rect {
  cursor: pointer;
  fill: #fff;
  fill-opacity: 0.8;
  stroke: #3182bd;
  stroke-width: 1.5px;
}

.node text {
  font: 10px sans-serif;
  pointer-events: none;
}

.link {
  fill: none;
  stroke: #9ecae1;
  stroke-width: 1.5px;
}

</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>

var margin = {top: 30, right: 20, bottom: 30, left: 20},
    width = 960,
    barHeight = 20,
    barWidth = (width - margin.left - margin.right) * 0.8;

var i = 0,
    duration = 400,
    root;

var diagonal = d3.linkHorizontal()
    .x(function(d) { return d.y; })
    .y(function(d) { return d.x; });

var svg = d3.select("body").append("svg")
    .attr("width", width) // + margin.left + margin.right)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.json("flare.json", function(error, flare) {
  if (error) throw error;
  root = d3.hierarchy(flare);
  root.x0 = 0;
  root.y0 = 0;
  update(root);

function toggleAll(d) {
                   if (d.children) {
                   d.children.forEach(toggleAll);
                  toggle(d);
                   }
               }

                 root.children.forEach(toggleAll);
                  toggle(root);
                  });


function update(source) {

  // Compute the flattened node list.
  var nodes = root.descendants();



  var height = Math.max(500, nodes.length * barHeight + margin.top + margin.bottom);

  d3.select("svg").transition()
      .duration(duration)
      .attr("height", height);

  d3.select(self.frameElement).transition()
      .duration(duration)
      .style("height", height + "px");

  // Compute the "layout". TODO https://github.com/d3/d3-hierarchy/issues/67
  var index = -1;
  root.eachBefore(function(n) {
    n.x = ++index * barHeight;
    n.y = n.depth * 20;
  });

  // Update the nodes.
  var node = svg.selectAll(".node")
    .data(nodes, function(d) { return d.id || (d.id = ++i); });

  var nodeEnter = node.enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
      .style("opacity", .5);

  // Enter any new nodes at the parent's previous position.
  nodeEnter.append("rect")
      .attr("y", -barHeight / 2)
      .attr("height", barHeight)
      .attr("width", barWidth)
      .style("fill", color)
      .on("click", click);

  nodeEnter.append("text")
      .attr("dy", 3.5)
      .attr("dx", 5.5)
      .text(function(d) { return d.data.name; });

   // Transition nodes to their new position.
  nodeEnter.transition()
      .duration(duration)
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
      .style("opacity", 1);

  node.transition()
      .duration(duration)
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
      .style("opacity", 1)
    .select("rect")
      .style("fill", color);

  // Transition exiting nodes to the parent's new position.
  node.exit().transition()
      .duration(duration)
      .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
      .style("opacity", 0)
      .remove();

  // Update the links.
  var link = svg.selectAll(".link")
    .data(root.links(), function(d) { return d.target.id; });

  // Enter any new links at the parent's previous position.
  link.enter().insert("path", "g")
      .attr("class", "link")
      .attr("d", function(d) {
        var o = {x: source.x0, y: source.y0};
        return diagonal({source: o, target: o});
      })
    .transition()
      .duration(duration)
      .attr("d", diagonal);

  // Transition links to their new position.
  link.transition()
      .duration(duration)
      .attr("d", diagonal);

  // Transition exiting nodes to the parent's new position.
  link.exit().transition()
      .duration(duration)
      .attr("d", function(d) {
        var o = {x: source.x, y: source.y};
        return diagonal({source: o, target: o});
      })
      .remove();

  // Stash the old positions for transition.
  root.each(function(d) {
    d.x0 = d.x;
    d.y0 = d.y;
  });
}



// 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(d);
}




function color(d) {
  return d._children ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c";
}

</script>

flare.json

 "name": "flare",
 "children": [
  {
   "name": "vis",
   "children": [
    {
     "name": "events",
     "children": [
      {"name": "DataEvent", "size": 2200, 
      "children": [
      {"name": "DataEvent", "size": 800,  "color" : "red"},
      {"name": "SelectionEvent", "size": 600,  "color" : "red"},
      {"name": "TooltipEvent", "size": 300,  "color" : "red"},
      {"name": "VisualizationEvent", "size": 250,  "color" : "red"},
      {"name": "TooltipEvent", "size": 250,  "color" : "red"},
      {"name": "DataEvent", "size": 525,  "color" : "red"},
      {"name": "SelectionEvent", "size": 375,  "color" : "red"},
      {"name": "TooltipEvent", "size": 265,  "color" : "red"},
      {"name": "VisualizationEvent", "size": 136,  "color" : "red"},
      {"name": "TooltipEvent", "size": 100,  "color" : "red"}
     ]


      },
      {"name": "SelectionEvent", "size": 1400, 
       "children": [
      {"name": "DataEvent", "size": 525,  "color" : "aqua"},
      {"name": "SelectionEvent", "size": 375,  "color" : "aqua"},
      {"name": "TooltipEvent", "size": 265,  "color" : "aqua"},
      {"name": "VisualizationEvent", "size": 136,  "color" : "aqua"},
      {"name": "TooltipEvent", "size": 100,  "color" : "aqua"}
     ]},
      {"name": "TooltipEvent", "size": 1200,  "color" : "green"},
      {"name": "VisualizationEvent", "size": 825,  "color" : "blue"},
      {"name": "TooltipEvent", "size": 400,  "color" : "purple"}
     ]
    }
   ]
  }
 ]
}

【问题讨论】:

    标签: javascript html css d3.js svg


    【解决方案1】:

    我正在尝试提供帮助。

    看着

    function toggleAll(d) {
                       if (d.children) {
                       d.children.forEach(toggleAll);
                      toggle(d);
                       }
                   }
    
                     root.children.forEach(toggleAll);
                      toggle(root);
                      });
    

    我认为

                      });
    

    不应该在那里。

    不错的递归函数!
    只需重新缩进即可:

    function toggleAll(d) {
      if (d.children) {
        d.children.forEach(toggleAll);
        toggle(d);
      }
    }
    

    调用它的一点调整:

    toggleAll(root);
    

    ^ 将全部关闭。注意:如果任何东西已经被关闭(通过点击),它将被打开,
    然后

    toggle(root);
    

    ^ 将重新打开(仅)root。

    希望这会有所帮助!

    【讨论】:

    • 感谢您查看@iAmOren,但我认为我不太明白:function toggleAll(d) { if (d.children) { d.children.forEach(toggleAll); toggle(d); } } toggleAll(root); toggle(root); 似乎没有把我带到那里......我哪里错了?
    【解决方案2】:

    在数据准备好后通过添加切换(单击)来重写代码。看下面的演示,不知道你是想要这个还是别的?

    var margin = {
            top: 30,
            right: 20,
            bottom: 30,
            left: 20
        },
        width = 960,
        barHeight = 20,
        barWidth = (width - margin.left - margin.right) * 0.8;
    
    var i = 0,
        duration = 400,
        root;
    
    var diagonal = d3.linkHorizontal()
        .x(function(d) {
            return d.y;
        })
        .y(function(d) {
            return d.x;
        });
    
    var svg = d3.select("body").append("svg")
        .attr("width", width) // + margin.left + margin.right)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    
    var flare = getFlare();
    //d3.json("flare.json", function(error, flare) {
    //    if (error) throw error;
        root = d3.hierarchy(flare);
        root.x0 = 0;
        root.y0 = 0;
        update(root);
    
        function toggleAll(d) {
            if (d.children) {
                d.children.forEach(toggleAll);
                //toggle(d);
                click(d)
            }
        }
    
        root.children.forEach(toggleAll);
        //toggle(root);
    //});
    
    
    function update(source) {
    
        // Compute the flattened node list.
        var nodes = root.descendants();
    
    
    
        var height = Math.max(500, nodes.length * barHeight + margin.top + margin.bottom);
    
        d3.select("svg").transition()
            .duration(duration)
            .attr("height", height);
    
        d3.select(self.frameElement).transition()
            .duration(duration)
            .style("height", height + "px");
    
        // Compute the "layout". TODO https://github.com/d3/d3-hierarchy/issues/67
        var index = -1;
        root.eachBefore(function(n) {
            n.x = ++index * barHeight;
            n.y = n.depth * 20;
        });
    
        // Update the nodes.
        var node = svg.selectAll(".node")
            .data(nodes, function(d) {
                return d.id || (d.id = ++i);
            });
    
        var nodeEnter = node.enter().append("g")
            .attr("class", "node")
            .attr("transform", function(d) {
                return "translate(" + source.y0 + "," + source.x0 + ")";
            })
            .style("opacity", .5);
    
        // Enter any new nodes at the parent's previous position.
        nodeEnter.append("rect")
            .attr("y", -barHeight / 2)
            .attr("height", barHeight)
            .attr("width", barWidth)
            .style("fill", color)
            .on("click", click);
    
        nodeEnter.append("text")
            .attr("dy", 3.5)
            .attr("dx", 5.5)
            .text(function(d) {
                return d.data.name;
            });
    
        // Transition nodes to their new position.
        nodeEnter.transition()
            .duration(duration)
            .attr("transform", function(d) {
                return "translate(" + d.y + "," + d.x + ")";
            })
            .style("opacity", 1);
    
        node.transition()
            .duration(duration)
            .attr("transform", function(d) {
                return "translate(" + d.y + "," + d.x + ")";
            })
            .style("opacity", 1)
            .select("rect")
            .style("fill", color);
    
        // Transition exiting nodes to the parent's new position.
        node.exit().transition()
            .duration(duration)
            .attr("transform", function(d) {
                return "translate(" + source.y + "," + source.x + ")";
            })
            .style("opacity", 0)
            .remove();
    
        // Update the links.
        var link = svg.selectAll(".link")
            .data(root.links(), function(d) {
                return d.target.id;
            });
    
        // Enter any new links at the parent's previous position.
        link.enter().insert("path", "g")
            .attr("class", "link")
            .attr("d", function(d) {
                var o = {
                    x: source.x0,
                    y: source.y0
                };
                return diagonal({
                    source: o,
                    target: o
                });
            })
            .transition()
            .duration(duration)
            .attr("d", diagonal);
    
        // Transition links to their new position.
        link.transition()
            .duration(duration)
            .attr("d", diagonal);
    
        // Transition exiting nodes to the parent's new position.
        link.exit().transition()
            .duration(duration)
            .attr("d", function(d) {
                var o = {
                    x: source.x,
                    y: source.y
                };
                return diagonal({
                    source: o,
                    target: o
                });
            })
            .remove();
    
        // Stash the old positions for transition.
        root.each(function(d) {
            d.x0 = d.x;
            d.y0 = d.y;
        });
    }
    
    
    
    // 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(d);
    }
    
    
    
    
    function color(d) {
        return d._children ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c";
    }
    function getFlare(){
      return {
     "name": "flare",
     "children": [
      {
       "name": "vis",
       "children": [
        {
         "name": "events",
         "children": [
          {
           "name": "DataEvent",
           "size": 2200,
           "children": [
            {
             "name": "DataEvent",
             "size": 800,
             "color": "red"
            },
            {
             "name": "SelectionEvent",
             "size": 600,
             "color": "red"
            },
            {
             "name": "TooltipEvent",
             "size": 300,
             "color": "red"
            },
            {
             "name": "VisualizationEvent",
             "size": 250,
             "color": "red"
            },
            {
             "name": "TooltipEvent",
             "size": 250,
             "color": "red"
            },
            {
             "name": "DataEvent",
             "size": 525,
             "color": "red"
            },
            {
             "name": "SelectionEvent",
             "size": 375,
             "color": "red"
            },
            {
             "name": "TooltipEvent",
             "size": 265,
             "color": "red"
            },
            {
             "name": "VisualizationEvent",
             "size": 136,
             "color": "red"
            },
            {
             "name": "TooltipEvent",
             "size": 100,
             "color": "red"
            }
           ]
          },
          {
           "name": "SelectionEvent",
           "size": 1400,
           "children": [
            {
             "name": "DataEvent",
             "size": 525,
             "color": "aqua"
            },
            {
             "name": "SelectionEvent",
             "size": 375,
             "color": "aqua"
            },
            {
             "name": "TooltipEvent",
             "size": 265,
             "color": "aqua"
            },
            {
             "name": "VisualizationEvent",
             "size": 136,
             "color": "aqua"
            },
            {
             "name": "TooltipEvent",
             "size": 100,
             "color": "aqua"
            }
           ]
          },
          {
           "name": "TooltipEvent",
           "size": 1200,
           "color": "green"
          },
          {
           "name": "VisualizationEvent",
           "size": 825,
           "color": "blue"
          },
          {
           "name": "TooltipEvent",
           "size": 400,
           "color": "purple"
          }
         ]
        }
       ]
      }
     ]
    }
    }
    .node rect {
      cursor: pointer;
      fill: #fff;
      fill-opacity: 0.8;
      stroke: #3182bd;
      stroke-width: 1.5px;
    }
    
    .node text {
      font: 10px sans-serif;
      pointer-events: none;
    }
    
    .link {
      fill: none;
      stroke: #9ecae1;
      stroke-width: 1.5px;
    }
    &lt;script src="https://d3js.org/d3.v4.min.js"&gt;&lt;/script&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-02
      • 1970-01-01
      • 2021-10-11
      • 2011-01-03
      • 2017-08-12
      • 1970-01-01
      • 2014-07-23
      • 1970-01-01
      相关资源
      最近更新 更多