如何更改 Cytoscape.js 网格中单个节点的颜色

Rob*_*jol 3 javascript cytoscape.js

如何将颜色更改为布局中已存在的节点或边缘(不删除/添加它)?

我有一个带有预选位置的节点布局,我想改变颜色(节点和边缘),但不是每个节点(或边缘)。我已经试过了

cy.style('background-color', 'color');
Run Code Online (Sandbox Code Playgroud)

,这允许更改颜色,但它会更改每个节点的颜色。

我只想改变一个节点的样式。

非常感谢

罗伯特

Ste*_* T. 5

解释:

嗨罗伯特,你是对的,这cy.style()改变了整个图表的风格。您可能没有注意到的是,您可以非常具体地指定要在哪个元素上执行此功能。

关于细胞景观选择器:

如果要选择特定类型的每个元素,可以调用:

cy.elements(); // this returns all edges and nodes
cy.nodes(); // this returns all nodes
cy.edges(); // this returns all edges
Run Code Online (Sandbox Code Playgroud)

如果您想获取一组特定的元素或特定的元素,您可以执行如下查询:

cy.elements/nodes/edges('[selector =/!= "property"]');   // selector can be id and the property the actual id
Run Code Online (Sandbox Code Playgroud)

解决方案:

要获得解决方案,您可以执行以下操作:

cy.nodes('[id = "yourId"]').style('background-color', 'desiredColor');
Run Code Online (Sandbox Code Playgroud)

或者将它绑定到一个事件,知道你的用例是什么:

cy.unbind('click);  // always unbind before binding an event to prevent binding it twiche/multiple times
cy.bind('click', 'node, edge', function(event) {
    let target = event.target;
  if (target.isEdge()) {
    target.style('line-color', 'green');
  } else {
    target.style({
      'background-color': 'white',
      'border-color': 'blue'
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

代码示例:

这是此方法的一个工作示例:

cy.elements(); // this returns all edges and nodes
cy.nodes(); // this returns all nodes
cy.edges(); // this returns all edges
Run Code Online (Sandbox Code Playgroud)
cy.elements/nodes/edges('[selector =/!= "property"]');   // selector can be id and the property the actual id
Run Code Online (Sandbox Code Playgroud)
cy.nodes('[id = "yourId"]').style('background-color', 'desiredColor');
Run Code Online (Sandbox Code Playgroud)