Cytoscape.js Show/Hide 单击按钮时图表中元素上的标签

Cytoscape.js Show/Hide labels on elements in the graph on button click

我有一个使用 cytoscape v3.15.2 的节点应用程序。我的样式设置如下

let cy = cytoscape({
            container: document.getElementById('graph-div'),
            style: [
                {
                    selector: 'node',
                    style: {
                        'label': 'data(id)',
                    }
               },
               {
                    selector: 'edge',
                    style: {
                        'label': (ele) => {
                            if(ele.data('type') === '1') return 'data(category1)';
                            if(ele.data('type') === '2') return 'data(category2)';
                            return value;
                        }
               }]
         }); 

现在,我尝试使用复选框 show/hide 元素上的标签。我已尝试执行以下操作:

cy.elements().style("label","");

但这不起作用。当我传递一个随机字符串而不是一个空字符串时,同样的事情会起作用,就像这样:cy.elements().style("label","random");。这样做会将图中所有元素的标签设置为隐藏。你能帮我怎么做吗?谢谢

您可以通过在样式表中指定 class 来管理 showing/hiding 标签,然后在单击按钮时切换它,如下例所示。

var cy = window.cy = cytoscape({
  container: document.getElementById('cy'),
  layout: {name: 'grid', rows: 2},
  style: [{
      selector: '.hasLabel',
      css: {
        'label': (ele) => {
          if(ele.isNode()) return ele.data('id');
          if(ele.isEdge()) return ele.data('weight');         
        }
      }
    }
  ],
  elements: {
    nodes: [{
        data: {
          id: 'n0'          
        }
      },
      {
        data: {
          id: 'n1'
        }
      },
      {
        data: {
          id: 'n2'
        }
      },
      {
        data: {
          id: 'n3'
        }
      }
    ],
    edges: [{
        data: {
          id: 'n0n1',
          source: 'n0',
          target: 'n1',
          weight: 3
        }
      },
      {
        data: {
          id: 'n1n2',        
          source: 'n1',
          target: 'n2',
          weight: 5
        }
      },
      {
        data: {
          id: 'n2n3',        
          source: 'n2',
          target: 'n3',
          weight: 7
        }
      }
    ]
  }
});

document.getElementById("labelButton").addEventListener("click", function() {
  cy.elements().toggleClass('hasLabel');
});
body {
  font: 14px helvetica neue, helvetica, arial, sans-serif;
}

#button {
  z-index = 1000;
}

#cy {
  height: 95%;
  width: 95%;
  left: 0;
  top: 50;
  z-index = 900;
  position: absolute;
}
<html>

<head>
  <meta charset=utf-8 />
  <meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
  <script src="https://unpkg.com/cytoscape@3.10.0/dist/cytoscape.min.js">
  </script>
</head>

<body>
  <button id="labelButton" type="button">Show/Hide Labels</button>
  <div id="cy"></div>
</body>

</html>