javascript D3 鼠标事件 -- Click & DragEnd
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19075381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
D3 Mouse Events -- Click & DragEnd
提问by FidEliO
In D3, if you defined a drag function like this:
在 D3 中,如果您定义了这样的拖动函数:
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.
原因是在“dragend”将触发之后点击将被触发。在我看来,应该有一个单独的点击事件,因为我看到 dragend 和 click 之间存在巨大差异。
To differentiate between clicking and end of a dragging event in an SVG element, what would be the solution?
要区分 SVG 元素中的单击和拖动事件的结束,有什么解决方案?
回答by Lars Kotthoff
The documentationhas 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.
这与stopPropagation()
后面的示例一起允许您控制触发和处理哪些事件。
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.
需要明确的是,区分拖动结束和单击事件完全取决于您。最简单的方法可能是在拖动发生时设置一个标志,并使用该标志来确定是否应处理adragend
或click
事件。
回答by phk
Since 4.9.0 there is .clickDistance()
with which you can control after which distance moved from where started dragging you won't get a click
event.
从 4.9.0 开始.clickDistance()
,您可以控制从开始拖动的位置移动的距离之后,您将不会收到click
事件。
Note that you might get any click
event at all if you remove the element from the DOM before release of the button (e.g. by using .raise()
in the drag
handler).
请注意,click
如果您在按钮释放之前从 DOM 中删除元素(例如,通过.raise()
在drag
处理程序中使用),您可能会得到任何事件。