Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

javascript - How to drag an svg group using d3.js drag behavior?

I am using D3js drag. single element is get dragged perfectly fine. but i want to drag a group of elements.How it can be done. Here is what is on my Js Fiddle link:

  function onDragDrop(dragHandler, dropHandler) {
        var drag = d3.behavior.drag();

    drag.on("drag", dragHandler)
    .on("dragend", dropHandler);
    return drag;
    }

    var g = d3.select("body").select("svg").append("g")
    .data([{ x: 50, y: 50 }]);

    g.append("rect")
    .attr("width", 40)
    .attr("height", 40)
    .attr("stroke", "red")
    .attr("fill","transparent")
    .attr("x", function (d) { return d.x; })
    .attr("y", function (d) { return d.y; })
    .call(onDragDrop(dragmove, dropHandler));

    g.append("text")
    .text("Any Text")
    .attr("x", function (d) { return d.x; })
    .attr("y", function (d) { return d.y; })
    .call(onDragDrop(dragmove, dropHandler));

    function dropHandler(d) {
       // alert('dropped');
    }

    function dragmove(d) {
        d3.select(this)
      .attr("x", d.x = d3.event.x)
      .attr("y", d.y = d3.event.y);
    }

I want to drag both rect and text simultaneously. Here is what I tried, but no luck. I think am missing something simple.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First off, the <g> element doesn't care about xand y attributes (as in: they're just ignored). You can use transform="translate(x,y)" instead.

Second, you will need to check that the element you get in the dragmove handler actually is the <g> element, and not a child element of it. This is because <g> elements have no actual hit area themselves. Their children do though, and the mouse events first go to the children then bubble up to the parent. You can inspect evt.target and evt.currentTarget to see this in action. target is the element that was hit originally, currentTarget is the event target that is currently handling the event (e.g the <g> element if the event bubbled up).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...