我正在D3.js上绘制强制导向图,并且想在双击节点时更改其颜色。 我的代码如下:
function dragstarted(d) {
d.fx = d.x;
d.fy = d.y;
d3.select(this).style("fill", "#ff0000");
}
在这里,我使用来更改节点拖动时的颜色(下面的代码只是代码的一部分。它可以正常工作。)
d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
而且,我想将拖动节点的颜色更改为其原始颜色,并编写了代码:
const node = svg ...
...
.on("dblclick", d => {
d.fx = null;
d.fy = null;
d3.select(this).style("fill", color(d));
})
其中
function color(d) {
if (d.group in grouparr){
return grouparr[d.group];
}
else {
return grouparr["else"]
}
}
和颜色信息存储在grouparr中。 color函数还用于初始化节点的颜色,例如:
const node = svg.append("g") // node
.attr("stroke", "#000")
.attr("stroke-width", 1.5)
.selectAll("circle")
.data(nodes)
.join("circle")
.attr("r", 5)
.attr("fill", d => color(d))
问题是,我编写了上述代码,以在用户双击时将节点的颜色更改为其原始颜色。但是,当我双击该节点时,其颜色保持不变!这段代码有什么问题?在代码中
const node = svg ...
...
.on("dblclick", d => {
d.fx = null;
d.fy = null;
d3.select(this).style("fill", color(d));
})
,d.fx = null和d.fy = null完美地工作,只有d3.select(this)...不起作用。