D3JS拖动SVG:G项在拖动前移动



>我按照将项目组拖到此处的教程进行操作 https://gist.github.com/enjalot/1378144

这就是我 http://jsfiddle.net/EwGPu/

var circle = svg.append('svg:g').selectAll('circle')
            .data(nodes, function(d) { return d.id; });
var g = circle.enter().append('svg:g').call(drag);
g.append('svg:circle').attr('class', 'node')
  .attr('cx', function (d) { return d.x; })
  .attr('cy', function (d) { return d.y; })
  .attr('r', 30)
  .style('fill', function(d) { return d3.rgb(colors(d.id)).brighter().toString(); })
  .style('stroke', function(d) { return d3.rgb(colors(d.id)).darker().toString(); });
g.append('svg:text')
  .attr('x', function (d) { return d.x + 0; })
  .attr('y', function (d) { return d.y + 4; })
  .attr('class', 'id')
  .text(function(d) { return d.id; });
var drag = d3.behavior.drag()
    .on('drag', function (d,i) {
        d.x += d3.event.dx;
        d.y += d3.event.dy;
        d3.select(this).attr("transform", function (d, i) {
            return "translate(" + [d.x,d.y] + ")";
        })
    });

但是,当我尝试拖动一个项目时,第一次拖动会将项目移离其当前坐标,但随后所有内容都会正常拖动。我不明白为什么第一次拖拽时的奇怪行为

问题是您使用两种设置坐标的方法 - 组的transform属性和圆的cxcy属性。没有任何拖拽,位置完全由后者决定。拖动时,您将设置组的平移,该平移在其他属性之上生效。也就是说,您正在将之前位于 (0,0) 处的组平移到圆的当前位置,导致坐标跳跃,因为cx cy位置保持不变。

如果您只使用其中一种方法,以后会为您省去一些麻烦。我在这里修改了您的 jsfiddle 以仅使用transform.这样,拖动可以按预期工作,无需任何跳转。此外,您只需要指定文本的相对偏移量而不是绝对偏移量。

最新更新