如何在vis.js中隐藏图形分支?

时间:2016-11-15 11:49:19

标签: javascript collapse expand vis.js vis.js-network

我能够通过单击具有以下内容的节点1205来显示vis.js中的部分图形,但是无法弄清楚如何在同一节点上再次单击时使展开的部分消失? / p>



var nodes = new vis.DataSet([
  {id: 2696, label: "l"}, 
  {id: 1205, label: "l"}, 
  {id: 2697, label: "l"}
]);

var edges = new vis.DataSet([
  {from: 2696, to: 2697}, 
  {from: 2696, to: 1205}
]);

var container = document.getElementById('mynetwork');
var data = {
  nodes: nodes,
  edges: edges
};

var network = new vis.Network(container, data, {});
network.on("click", function(e) {
  tw_id = 1205;
  if (e.nodes[0] == tw_id) {
    sel_id = e.nodes[0];
    var node = nodes.get(e.nodes[0]);
    nodes.add([
      {id: 2021, label: "l"}, 
      {id: 2047, label: "l"}
    ]);
    edges.add([
      {from: 1205, to: 2021}, 
      {from: 1205, to: 2047}
    ]);
    nodes.update(node);
  }
});

#mynetwork {
  width: 400px;
  height: 300px;
  border: 1px solid lightgray;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.17.0/vis.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.17.0/vis.min.js"></script>
<div id="mynetwork"></div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

以下是基于@ pgoldweic选项实现此功能的示例,以及预定义节点1205上每次点击将显示/未显示的边和节点。

代码维护一个布尔值,指示下一个操作是显示还是隐藏其他节点。对于hidden属性,show为false,hide为true

var nodes = new vis.DataSet([
  {id: 2696, label: "2696", hidden: false}, 
  {id: 1205, label: "1205", hidden: false}, 
  {id: 2697, label: "2697", hidden: false},
  {id: 2021, label: "2021", hidden: true},
  {id: 2047, label: "2047", hidden: true}
]);

var edges = new vis.DataSet([
  {id: 'e1', from: 2696, to: 2697, hidden: false}, 
  {id: 'e2', from: 2696, to: 1205, hidden: false},
  {id: 'e3', from: 1205, to: 2021, hidden: true},
  {id: 'e4', from: 1205, to: 2047, hidden: true}
]);

var container = document.getElementById('mynetwork');
var data = {
  nodes: nodes,
  edges: edges
};

var network = new vis.Network(container, data, {});

// true=hide; false=show
var toggle = false;
network.on("click", function(e) {
  tw_id = 1205;
  if (e.nodes[0] == tw_id) {
    nodes.update([
      {id: 2021, hidden: toggle},
      {id: 2047, hidden: toggle}
    ]);
    edges.update([
      {id: 'e3', hidden: toggle},
      {id: 'e4', hidden: toggle}
    ]);
    network.fit();
    // switch toggle
    toggle = !toggle;
  }
});
#mynetwork {
  width: 400px;
  height: 300px;
  border: 1px solid lightgray;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.17.0/vis.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.17.0/vis.min.js"></script>
<div id="mynetwork"></div>

答案 1 :(得分:1)

只要您跟踪哪个节点和边缘是给定节点的扩展区域的一部分,您始终可以使用vis.js更新功能隐藏它们。例如,要隐藏ID为&#39; id1&#39;的节点,您可以调用:

nodes.update([{id: 'id1', hidden: true}]);

(请注意,update期望数组作为参数)。以同样的方式,您可以通过调用隐藏边缘:

edges.update([{id: 'edge1', hidden: true}]);

希望这有帮助!