我有一个 svg 元素,我希望能够分别单击和拖动。据我所知,在 D3 中,单击会触发“拖动结束”事件(也可能是拖动开始?)。在下面的代码中,只需单击圆圈即可显示红色轮廓:
var svg = d3.select('body').append('svg');
var g = svg.append('g');
var c = g.append('circle').attr('r', 20).attr('cx', 25).attr('cy', 25)
.call(d3.drag().on('drag', dragged).on('end', end))
.on('click', clicked);
function dragged() {
d3.select(this).attr('fill', 'green').attr('cx', d3.event.x).attr('cy', d3.event.y);
}
function end() {
d3.select(this).attr('fill', 'red').attr('stroke', 'red').attr('stroke-width', 5);
}
function clicked() {
if (d3.event.defaultPrevented) return;
d3.select(this).attr('fill', 'blue');
}
Run Code Online (Sandbox Code Playgroud)
似乎大多数关于点击和拖动的问题和块似乎都想抑制拖动时的点击动作,所以不相关。
由于 mouseup 指示点击完成和拖动结束,您可以跳过点击事件并简单地添加一些逻辑来确定是否发生拖动:
// track action:
var wasMoved = false;
// Drag event:
function dragged() {
d3.select(this).attr('fill', 'green').attr('cx', d3.event.x).attr('cy', d3.event.y);
wasMoved = true; // or alternatively, measure the change in distance.
}
// Mouse up event: drag end & click:
function end() {
if(wasMoved) {
// It was a drag:
d3.select(this).attr('fill', 'red').attr('stroke', 'red').attr('stroke-width', 5);
}
// Otherwise it was a click:
else {
d3.select(this).attr('fill', 'blue');
}
wasMoved = false; // reset for next drag.
}
Run Code Online (Sandbox Code Playgroud)
现在我们只能在 mouseup 上触发一个动作:拖动结束或我们想要的点击:
// track action:
var wasMoved = false;
// Drag event:
function dragged() {
d3.select(this).attr('fill', 'green').attr('cx', d3.event.x).attr('cy', d3.event.y);
wasMoved = true; // or alternatively, measure the change in distance.
}
// Mouse up event: drag end & click:
function end() {
if(wasMoved) {
// It was a drag:
d3.select(this).attr('fill', 'red').attr('stroke', 'red').attr('stroke-width', 5);
}
// Otherwise it was a click:
else {
d3.select(this).attr('fill', 'blue');
}
wasMoved = false; // reset for next drag.
}
Run Code Online (Sandbox Code Playgroud)
var svg = d3.select('body').append('svg');
var g = svg.append('g');
var drag = d3.drag().on("drag", dragged).on("end",end);
var c = g.append('circle')
.attr('r', 20).attr('cx', 25).attr('cy', 25)
.call(drag)
var wasMoved = false;
function dragged() {
d3.select(this).attr('fill', 'green').attr('cx', d3.event.x).attr('cy', d3.event.y);
wasMoved = true;
}
function end() {
if(wasMoved) {
// It was a drag:
d3.select(this).attr('fill', 'red').attr('stroke', 'orange').attr('stroke-width', 5);
}
// It was a click:
else {
d3.select(this).attr('fill', 'blue');
}
wasMoved = false;
}Run Code Online (Sandbox Code Playgroud)