javascript - 将元素发送到前台时不会发出点击

标签 javascript d3.js

在创建简单的图表组件时,我无法正确组合拖动、将拖动的元素发送到前台并单击。

我想要实现的目标:

  1. 拖动或单击的元素应发送到前台(在其他元素前面)
  2. 不应为拖动的元素发出选择操作
  3. 点击或点击应选择一个元素

它适用于其他元素前面的元素,但单击任何其他元素只会将其发送到前面,而无需单击。你能帮我吗?

JSFiddle:http://jsfiddle.net/1o1dnpsw/2/

HTML

<svg width="250" height="150">
</svg>
<div id="msg">click on rectangle or drag it</div>
<p>Problem: while clicking on the element which is not on the foreground (yellow) the click is not emitted.</p>

CSS

body { font-family: sans-serif; font-size: 12px; } 
svg { border: 1px solid gray; }
svg rect { border: 1px solid gray; }
div { border: 1px dotted gray; margin-top: 10px; width: 250px; height: 25px;
  text-align: center; line-height: 25px; }

脚本

function select() {
    document.getElementById('msg').innerText =
        'selected at ' + new Date().getTime();
}

function addBox(color, x, y) {
    var r = d3.selectAll('svg').append('rect')
        .attr('x', x).attr('y', y)
        .attr('width', 50).attr('height', 50)
        .attr('fill', color)
        .on('mousedown', function () {
            // move element to foreground
            this.parentNode.appendChild(this);
        })
        .on('click', function () {
            // do not click when dragged
            if (d3.event.defaultPrevented) {
                return;
            }
            select();
        })
        .call(d3.behavior.drag()
            .origin(function () { return { x : x, y : y }; })
            .on('dragstart', function () {
                d3.event.sourceEvent.preventDefault();
            })
            .on('drag', function () {
                x = d3.event.x;
                r.attr('x', x);
                y = d3.event.y;
                r.attr('y', y);
            })
            .on('dragend', function () {
            }));
}

addBox('#FFC60D', 10, 10);
addBox('#161EFF', 40, 40);

最佳答案

已修复。

fiddle :http://jsfiddle.net/1o1dnpsw/3/

向函数 addBox() 添加了 2 个变量:

var oldX;
var oldY;

并将拖动和拖尾事件更改为:

.on('drag', function () {
    oldX = r.attr('x');
    oldY = r.attr('y');
    x = d3.event.x;
    r.attr('x', x);
    y = d3.event.y;
    r.attr('y', y);
})
.on('dragend', function () {
    if (x == oldX && y == oldY) {
        select();
    }
}));

关于javascript - 将元素发送到前台时不会发出点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26290435/

相关文章:

javascript - 执行 TestCafe 断言的正确方法是什么

javascript - 通过jQuery ajax请求获取数据

javascript - 在 d3.js 生成的新元素中获取 Angular 以执行 ng-if

javascript - 如何仅在 Angular js 中从 tsv 加载数据后才呈现指令

javascript - 如何让 jQuery 验证允许数字包含破折号

javascript - AJAX接收多个数据

javascript - 获取表格中行的背景以通过单击更改?

html - d3地理 map 溢出

javascript - d3.format 变量的千位分隔符?

javascript - 文本和输入元素以相同的方式附加和赋予属性。显示文本但不显示输入。为什么?