标签是否可以默认隐藏,但在选择节点时显示?

Can labels be hidden by default, but shown when the node is selected?

我希望我的图表默认没有标签,但是当我 select 一个节点时,它的标签会显示出来。有 chosen.label that seems promising, but I still don't know how to write the function. There is also a question about scaling.label,但如其中所示,它似乎也不起作用。

另一种方法是使用复选框来打开和关闭标签。参见:

这可以通过结合使用 chosen.label 选项和 transparent 字体颜色来实现。

在选项对象中首先将节点的默认字体颜色设置为透明,然后在chosen.label内将其调整为可见颜色。

var options = {
  nodes: {
    font: {
      // Set default label font color to transparent
      color: "transparent"
    },
    chosen: {
      label: function(values, id, selected, hovering) {
        // Adjust label font color so it is visible
        // Updates to the values object are applied to the network
        values.color = "#343434";
      }
    }
  }
};

工作示例如下。

// create an array with nodes
var nodes = new vis.DataSet([
  { id: 1, label: "Node 1" },
  { id: 2, label: "Node 2" },
  { id: 3, label: "Node 3" }
]);

// create an array with edges
var edges = new vis.DataSet([
  { from: 1, to: 3 },
  { from: 1, to: 2 },
  { from: 3, to: 3 },
]);

// create a network
var container = document.getElementById("mynetwork");
var treeData = {
  nodes: nodes,
  edges: edges,
};
var options = {
  nodes: {
    font: {
      // Set default label font color to transparent
      color: "transparent"
    },
    chosen: {
      label: function(values, id, selected, hovering) {
        // Adjust label font color so it is visible
        // Updates to the values object are applied to the network
        values.color = "#343434";
      }
    }
  }
};
var network = new vis.Network(container, treeData, options);
#mynetwork {
  width: 600px;
  height: 180px;
  border: 1px solid lightgray;
}
<script src="https://visjs.github.io/vis-network/standalone/umd/vis-network.min.js"></script>
<div id="mynetwork"></div>