據我所知,該問題是,拖動工作有圓圈但不與羣組,因爲某些原因
您正在操縱使用cx和cy屬性拖動節點。 g
元素沒有這些,所以這不會達到你想要的東西,即使node
包含組,而不是圈:
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
如前所述,node = g.append("circle")
意味着你實際上並沒有操縱g
元素不管怎麼說,這這就是爲什麼你的圈子在打勾或拖動時移動。
相反,保持節點選擇g
元素,並操縱transform
屬性:
// the group representing each node:
node = node.enter().append("g").merge(node);
// the circle for each group
node.append("circle")
.classed('node', true).attr('id', id)
.text(id)
.attr("r", 25).attr("fill", function(d) { return color(d.id); });
// the text for each group
node.append("text")
.classed('text', true)
.attr("text-anchor", "start")
.attr("dx", 6).text(id).merge(node);
然後點擊或拖動事件,只需更新改造:
蜱:
node.attr("transform",function(d) { return "translate("+d.x+","+d.y+")" ;});
拖動:
d.x = d3.event.x;
d.y = d3.event.y;
d3.select(this).attr("transform",function(d) { return "translate("+d.x+","+d.y+")" ;});
這是updated fiddle。
就是這樣。謝謝你,安德魯!編輯是微不足道的,但我無法用頭圍住它。 – one2gov