【问题标题】:D3js drag vs clickD3js拖动与点击
【发布时间】:2016-05-30 15:42:00
【问题描述】:

我正在使用节点的拖放和单击功能编写 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一样?

【问题讨论】:

  • 我正在使用 Chromium,它的行为类似于 Firefox。如果在 onClick 中在flashRect(); 之后添加d3.event.stopPropagation();,是否有效?
  • @TimB add stopPropagation to onClick 函数不会做任何事情,因为我需要停止触发 onDrag 并且 onDrag 在 onClick 之前触发
  • 我猜.on('dragend', onDragStart)应该是.on('dragstart', onDragStart)

标签: javascript google-chrome firefox d3.js


【解决方案1】:
   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);
                });
            });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 2016-02-28
    相关资源
    最近更新 更多