【问题标题】:d3js drag svg:g item move before dragd3js拖动svg:g项目在拖动前移动
【发布时间】:2013-10-04 23:24:59
【问题描述】:

我按照这里的拖动组的教程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] + ")";
        })
    });

但是,当我尝试拖动一个项目时,第一次拖动会将项目从其当前坐标移开,但随后一切都会正常拖动。我不明白为什么在第一次拖动时会出现奇怪的行为

【问题讨论】:

    标签: svg d3.js drag


    【解决方案1】:

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

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

    【讨论】:

    • 完美的解释。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多