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
390 views
in Technique[技术] by (71.8m points)

javascript - D3 Mouse Events -- Click & DragEnd

In D3, if you defined a drag function like this:

var drag = d3.behavior.drag()
        .on("drag", function () {alert("drag")})
        .on("dragend", function () {alert("dragEnd")});

You really cannot do the following:

d3.select("#text1")
.on("click", function(d,i) {alert("clicked")})
.call(drag);

Reason is that the click will get fired after that the "dragend" will fire . In my opinion there should be a separate event for clicking because I see a huge difference between dragend and click.

To differentiate between clicking and end of a dragging event in an SVG element, what would be the solution?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The documentation has some explicit examples for this:

When registering your own click listener on draggable elements, you can check whether the click event was suppressed as follows:

selection.on("click", function() {
  if (d3.event.defaultPrevented) return; // click suppressed
  console.log("clicked!");
});

This, along with the stopPropagation() example immediately afterwards, allows you to control which events are fired and handled.

To be clear, differentiating between a drag end and click event is entirely down to you. The easiest way to do this is probably to set a flag when dragging takes place and use that flag to determine whether a dragend or click event should be handled.


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

...