始终在d3中拖动后抑制点击事件 [英] Always suppress a click event after drag in d3

查看:1529
本文介绍了始终在d3中拖动后抑制点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击和拖动事件的解除链接在之前的一些问题中进​​行了讨论,例如 this one < a>

Decoupling of click and drag events is discussed in some previous questions here, e.g. this one

通常情况下,建议使用 if(d3.event.defaultPrevented === false){...} 。但是,这似乎不工作(至少在一些浏览器)如果mouseup和mousedown不在同一个元素。 请考虑这个jsfiddle (代码如下)。这里是我想要的行为:单击任何地方在SVG触发器单击事件(矩形闪烁),拖动任何地方在SVG拖动矩形。观察到的行为(Chrome 33):如果点击的mousedown在矩形内部并且mouseup在外部,则拖动和点击事件都会触发。如果mousedown和mouseup都在里面或者两者都在外面,则不会触发点击事件。

Typically, it is recommended to use if (d3.event.defaultPrevented === false) {...} in the click handler. However, this doesn't seem to work (at least in some browsers) if mouseup and mousedown are not in the same element. Consider this jsfiddle (code below). Here is the behavior I want: click anywhere in SVG triggers click event (rectangle flashes), drag anywhere in SVG drags the rectangle. 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. If both mousedown and mouseup are inside or both are outside, click event is not triggered.

有人可以解释为什么如果mouseup和mousedown不在同一个元素中而触发点击事件,以及如何可靠地防止这种情况发生?

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?

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");
    }
}


推荐答案

dragBehavior到矩形而不是整个svg元素。
以下是修正的小调链接 http://jsfiddle.net/Mn4Uk/27/

Add dragBehavior to the rectangle instead of the whole svg element. Here is the fiddle link with the fix http://jsfiddle.net/Mn4Uk/27/

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

这篇关于始终在d3中拖动后抑制点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆