简体   繁体   English

在d3中拖动后始终禁止单击事件

[英]Always suppress a click event after drag in d3

Decoupling of click and drag events is discussed in some previous questions here, eg this one 在此处的一些先前问题中讨论了点击和拖动事件的解耦,例如这一问题

Typically, it is recommended to use if (d3.event.defaultPrevented === false) {...} in the click handler. 通常,建议在单击处理程序中使用if (d3.event.defaultPrevented === false) {...} However, this doesn't seem to work (at least in some browsers) if mouseup and mousedown are not in the same element. 但是,如果mouseup和mousedown不在同一个元素中,这似乎不起作用(至少在某些浏览器中)。 Consider this jsfiddle (code below). 考虑一下这个jsfiddle (下面的代码)。 Here is the behavior I want: click anywhere in SVG triggers click event (rectangle flashes), drag anywhere in SVG drags the rectangle. 这是我想要的行为:单击SVG触发器中的任何位置单击事件(矩形闪烁),在SVG中的任何位置拖动拖动矩形。 Observed behavior (Chrome 33): if the mousedown of the click is inside the rectangle and mouseup is outside, both the drag and click events trigger. 观察到的行为(Chrome 33):如果点击的moused在矩形内并且mouseup在外面,则拖动和单击事件都会触发。 If both mousedown and mouseup are inside or both are outside, click event is not triggered. 如果mousedown和mouseup都在内部或两者都在外面,则不会触发click事件。

Can someone explain why the click event is triggered if mouseup and mousedown are not in the same element, and how to reliably prevent this from happening? 有人可以解释为什么如果mouseup和mousedown不在同一个元素中而触发click事件,以及如何可靠地防止这种情况发生?

var container, rect, dragBehavior;

svg = d3.select('svg').attr("width", 500).attr("height", 300);
container = svg.append('g');
rect = container.append('rect').attr('width', 100).attr('height', 100);

dragBehavior = d3.behavior.drag()
    .on('dragend', onDragStart)
    .on('drag', onDrag)
    .on('dragend', onDragEnd);

svg.call(dragBehavior).on('click', onClick);

function flashRect() { rect.attr('fill', 'red').transition().attr('fill', 'black'); }

function onDragStart() { console.log('onDragStart'); }

function onDrag() {
    console.log('onDrag');
    var x = (d3.event.sourceEvent.pageX - 50);
    container.attr('transform', 'translate(' + x + ')');
}

function onDragEnd() { console.log('onDragEnd'); }

function onClick(d) {
    if (d3.event.defaultPrevented === false) {
        console.log('onClick');
        flashRect();
    } else {
        console.log("default prevented");
    }
}

Add dragBehavior to the rectangle instead of the whole svg element. 将dragBehavior添加到矩形而不是整个svg元素。 Here is the fiddle link with the fix http://jsfiddle.net/Mn4Uk/27/ 这是与修复http://jsfiddle.net/Mn4Uk/27/的小提琴链接

rect
.call(dragBehavior)
.on('click', onClick);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM