要在点击时突出显示节点和已连接的节点/路径,我将遵循以下示例:http://www.coppelia.io/2014/07/an-a-to-z-of-extra-features-for-the-d3-force-layout/
我插入了这段代码:
//---Insert-------
//Toggle stores whether the highlighting is on
var toggle = 0;
//Create an array logging what is connected to what
var linkedByIndex = {};
for (i = 0; i < data.nodes.length; i++) {
linkedByIndex[i + "," + i] = 1;
};
data.links.forEach(function (d) {
linkedByIndex[d.source.index + "," + d.target.index] = 1;
});
//This function looks up whether a pair are neighbours
function neighboring(a, b) {
return linkedByIndex[a.index + "," + b.index];
}
function connectedNodes() {
if (toggle == 0) {
//Reduce the opacity of all but the neighbouring nodes
d = d3.select(this).node().__data__;
circle.style("opacity", function (o) {
return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1;
});
path.style("opacity", function (o) {
return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1;
});
//Reduce the op
toggle = 1;
} else {
//Put them back to opacity=1
circle.style("opacity", 1);
path.style("opacity", 1);
toggle = 0;
}
}
我将此行添加到节点:
.on('click', connectedNodes)
结果是,当单击节点时,它的连接路径会正确突出显示,但节点及其连接的节点不会突出显示。相反,所有节点都减少到0.1不透明度。如何更改代码以正确突出显示已连接的节点?