質問

Hey im using this d3 tree.

Is there a possibility to close all other child nodes when i click on a node with the same parent. I think it should be something like this but i have no idea to modify it:

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

  nodeExit.select("circle")
      .attr("r", 1e-6);
  nodeExit.select("text")
      .style("fill-opacity", 1e-6);

So for example if you look on the working example:

  • Topic_2 is clicked and its children (Subtopic 4, Subtopic 5, Subtopic 6) are shown

  • I click on Topic_1 - children of Topic_1 open

  • Children of Topic_2 shall be closed

役に立ちましたか?

解決

This fiddle does what you want. I just made the following change:

// Toggle children
function toggle(d) {
    console.log(d);
  if (d.children) {
    d._children = d.children;
    d.children = null;
  }
  else {
    closeSiblings(d);
    d.children = d._children;
    d._children = null;
  }
}

function closeSiblings(d) {
    if (!d.parent) return; // root case
    d.parent.children.forEach(function(d1) {
        if (d1 === d || !d1.children) return;
        d1._children = d1.children;
        d1.children = null;
    });
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top