2014-08-28 41 views
0

jsFiddle Here获取的这个id属性与D3

lineID = d3.select(this.firstChild).attr('id'); // setting the line id 
textID = d3.select(this.lastChild).attr('id'); // setting the text id 

在这种情况下,我想行与标签移动它拖时。
所以只有线的x2和y2属性会被更新,并且线的x1和y1应该保持不变。
这里firstChild和lastChild的用法可能不是理想的解决方案。 x1和y1现在硬编码了,我不知道如何动态返回值。

+0

你为什么不简单地翻译'g'元素? – 2014-08-28 08:58:07

+0

@LarsKotthoff他希望'x1','y1'保持不变。如果你翻译'g's,那么这是行不通的(而且他没有它们,可惜...) – Oleg 2014-08-28 09:14:17

回答

0

.text选择上调用您的拖动,如this example,而不是svg根元素。

g.selectAll(".text") 
    ... 
    .call(drag); 

然后,访问IDS:

var textID = this.id; // this = current text element 
var lineID = 'line' + textID.slice(-1); // your custom line id 

编辑

另外,如果你想离开x1y1一样的,你可以忽略它们在你的更新行为:

d3.select("#"+ lineID) 
    .attr("x2", newx2) 
    .attr("y2", newy2); 

并且因此.text不会在拖动时跳跃,只需使用transform,而无需设置xy偏移量(默认情况下它们将为0)。

g.selectAll(".text") 
    ... // no .attr('x', ...) or y here 
    .attr("transform", function(d) { 
     return "translate(" + (d.x + 10) + "," + (d.y - 30) + ")"; 
    }) 
    ...; 

这是DEMO

+0

不知何故,翻译位在实际项目中不能很好地工作,可能没有正确设置它。不管怎样,谢谢。 – user2901633 2014-08-29 02:55:29