最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - D3: d3.behavior.drag - Stack Overflow

matteradmin6PV0评论

I'm trying this example and I applied the d3.behavior.drag with the function

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 ] + ")"
            })
        });

Please see my example here.

My problem is after dragging the svg.

When I click on an element the zoom isn't well apllied.

For instance, the root disappear...

How can I fix this situation?

Thanks, Carlos.

I'm trying this example and I applied the d3.behavior.drag with the function

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 ] + ")"
            })
        });

Please see my example here.

My problem is after dragging the svg.

When I click on an element the zoom isn't well apllied.

For instance, the root disappear...

How can I fix this situation?

Thanks, Carlos.

Share Improve this question asked May 24, 2013 at 14:14 carlos-gvacarlos-gva 213 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

The problem is that when you try to drag the elements the click event is also fired and both the event handlers are getting executed.

You need to ignore the click event if it was suppressed (i.e. when you are dragging).

Modify your click event handler as

function click(d) {
    // Ignore the click event if it was suppressed
    if (d3.event.defaultPrevented){
     return;
    }
    path.transition()
      .duration(750)
      .attrTween("d", arcTween(d));
    };

Given in your case that an element can be dragged and clicked, in addition to prashant's answer, you'll want to suppress the click on drag as follows:

drag.on("dragstart", function() {
  d3.event.sourceEvent.stopPropagation(); // silence other listeners
});

See http://bl.ocks/mbostock/6123708 for an example :-)

use this, d3.event.sourceEvent.stopPropagation();

Post a comment

comment list (0)

  1. No comments so far