首页 > 解决方案 > cytoscape js隐藏新布局不包含的元素

问题描述

我有一个问题,我还没有找到解决方案。我有一个图形,它位于 cose-bilkent 布局中,我想创建一个新布局来显示选择节点的子节点。我正在使用函数 makeLayout() 但问题是我仍然看到新布局不包含的节点。

data = dataArray[0];
style = dataArray[1];

var nodes = [];
var edges = [];
for (var i=0; i<data.length; i++) {
  if (data[i].group == 'nodes') {
    nodes.push(data[i]);
  }
  else if (data[i].group == 'edges') {
    edges.push(data[i]);
  }
}
var elements = {nodes, edges};

var cy = window.cy = cytoscape({
  container: document.getElementById('cy'),
  style: style,
  elements: elements,

  ready: function(){
    window.cy = this;
  }
});

var layout = cy.layout({name: 'cose-bilkent'});
layout.run();

function highlight( node ){

var nodeId = node.id();
var childNodes = cy.nodes('node[parent="'+nodeId+'"]');
var nhood = lastHighlighted = childNodes;
var others = lastUnhighlighted = cy.elements().not( nhood );


others.style("visibility", "hidden");
nhood.style("visibility", "visible");

  var layoutZoom = nhood.makeLayout({
      name: 'grid',
      fit: true,
      elements: nhood
  });

  layout.stop();
  layoutZoom.run();
}

function clear(){
  cy.elements().style("visibility", "visible");
  layout.run();
}

cy.on('select unselect', 'node', function(e){
var node = cy.$('node:selected');

if(node.nonempty()){
  Promise.resolve().then(function(){
    return highlight(node);
  });
}
else {
  clear();
}
});

我做错了什么隐藏所有节点。

完整代码在这里:https ://github.com/bartequ/inz

标签: javascriptlayoutcytoscape.js

解决方案


看看我的代码笔,为您的问题提供一个功能齐全的解决方案:)

cy.on('click', 'node', function(node) {
  // get nodes id
  var nodeId = node.target.id();

  // add all successors (nodes and edges) to a collection
  var childNodes = cy.nodes('[id="'+nodeId+'"]').successors();   

  // add clicked node to collection
  childNodes = childNodes.add(node.target);  

  // add other nodes to other collection
  var others = cy.elements().not(childNodes);  

  //cy.remove() returns the deleted nodes and edges, so that you can just do cy.add() afterwards
  referenceNodes = cy.remove(others);  

  // just call a new layout
  cy.elements().makeLayout({'name': 'dagre', 'padding': 5 }).run();  
});

推荐阅读