D3 鼠标事件——点击&拖尾 [英] D3 Mouse Events -- Click & DragEnd
问题描述
在 D3 中,如果您定义了这样的拖动功能:
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);
原因是在dragend"将触发之后点击将被触发.我认为应该有一个单独的点击事件,因为我发现 dragend 和 click 之间存在巨大差异.
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.
要区分 SVG 元素中的单击和拖动事件的结束,有什么解决方案?
To differentiate between clicking and end of a dragging event in an SVG element, what would be the solution?
推荐答案
文档对此有一些明确的例子:
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!");
});
这与紧随其后的 stopPropagation()
示例一起,允许您控制触发和处理哪些事件.
This, along with the stopPropagation()
example immediately afterwards, allows you to control which events are fired and handled.
需要明确的是,区分拖动结束和点击事件完全取决于您.最简单的方法可能是在拖动发生时设置一个标志,并使用该标志来确定是否应该处理 dragend
或 click
事件.
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.
这篇关于D3 鼠标事件——点击&拖尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!