D3js拖动与点击

时间:2016-05-30 15:42:00

标签: javascript google-chrome firefox d3.js

我使用拖放编码d3js树并单击节点的功能。我遇到了这个例子http://jsfiddle.net/langdonx/fe5gn/

var container,
    rect,
    dragBehavior,
    wasDragged = false;

container = d3.select('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);

container
    .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 + ')');

    wasDragged = true;
}

function onDragEnd() {
    if (wasDragged === true) {
        console.log('onDragEnd');

        // always do this on drag end
        flashRect();
    }

    wasDragged = false;
}

function onClick(d) {
    if (d3.event.defaultPrevented === false) {
        console.log('onClick');

        // only do this on click if we didn't just finish dragging
        flashRect();
    }
}

但是这个例子的行为与chrome上的行为不同,就像在firefox上一样。 当我点击矩形时:

  • Chrome输出:OnDrag,OnDragEnd,OnClick
  • Firefox输出:OnClick

当我拖放矩形时:

  • Chrome输出:OnDrag,OnDragEnd
  • Firefox输出:OnDrag,OnDragEnd

有没有办法让chrome在点击时的行为与firefox相同?

1 个答案:

答案 0 :(得分:0)

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

   container
       .on("mousedown", function() { 
                d3.event.stopPropagation();

                d3.select(this).on("mouseup", onClick);
                d3.select(this).on("mousemove",  function()
                {
                    d3.select(this).call(dragBehavior);
                });
            });