如何在使用d3拖动时禁用鼠标悬停和mouseout事件?

时间:2017-01-17 19:12:23

标签: javascript d3.js mouseover drag

我有一堆svg圆圈,在悬停时显示工具提示,可以在画布上拖动。对于mouseovermouseout以及dragstartdragend,我正在计算要记录的事件。

但是,当拖动一个圆圈时,我不希望它继续触发鼠标悬停事件被记录 - 理想情况下,我希望工具提示继续显示,但不会生成鼠标悬停事件的日志如果它也被拖了。

我尝试过多次尝试禁用鼠标悬停事件并在dragstart和dragend上重新启用它,包括$(this).on('mouseover', function() { return false; });$(this).on('mouseover', mouseover);以及尝试取消绑定并重新绑定鼠标悬停事件。代码如下。

// define drag behavior
drag = d3.behavior.drag()
    .origin(function(d) { return {x: d['x'], y: d['y']}; })
    .on('dragstart', function(d) {
        dragStart = new Date(); 
    }).on('drag', dragged)
    .on('dragend', function(d) {
        dragEnd = new Date(); 
        // units are seconds
        var elapsedTime = (dragEnd - dragStart) / 1000;
        console.log("elapsed drag time: " + elapsedTime);
        // TODO: generate the log of the drag ---
    });

// create circles
var circles = svg
    .selectAll('circle')
    .data(data)
    .enter().append('circle')
    .attr('class', 'circle')
    .attr('cx', function(d) { return d['x']; })
    .attr('cy', function(d) { return d['y']; })
    .attr('r', radius)
    .classed('unsorted', true)
    .call(drag)
    .on('click', clicked)
    .on('mouseover', mouseover)
    .on('mouseout', mouseout);

// define mouseover behavior
function mouseover(d) {
    mouseoverStart = new Date();
    tip.show(d);
}

// define mouseout behavior
function mouseout(d) {
    tip.hide(d);
    mouseoverEnd = new Date();
    // units are seconds
    var elapsedTime = (mouseoverEnd - mouseoverStart) / 1000;
    console.log("elapsed mouseover time: " + elapsedTime);
    // TODO: generate the log of the mouseover --
}

我是如何实现这一目标的?鼠标悬停功能中是否有一种方法可以检查该元素是否也被拖动?

1 个答案:

答案 0 :(得分:2)

只需使用外部范围中的变量标记拖动:

var isDragging = false; 
drag = d3.behavior.drag()
    .origin(function(d) { return {x: d['x'], y: d['y']}; })
    .on('dragstart', function(d) {
        isDragging = true;
        dragStart = new Date(); 
    }).on('drag', dragged)
    .on('dragend', function(d) {
        dragEnd = new Date(); 
        // units are seconds
        var elapsedTime = (dragEnd - dragStart) / 1000;
        console.log("elapsed drag time: " + elapsedTime);
        // TODO: generate the log of the drag ---
        isDragging = false;
    });

function mouseout(d) {
    tip.hide(d);
    mouseoverEnd = new Date();
    // units are seconds
    var elapsedTime = (mouseoverEnd - mouseoverStart) / 1000;
    if (!isDragging) console.log("elapsed mouseover time: " + elapsedTime);
    // TODO: generate the log of the mouseover --
}