在创建简单的图表组件时,我无法正确组合拖动、将拖动的元素发送到前台并单击。
我想要实现的目标:
- 拖动或单击的元素应发送到前台(在其他元素前面)
- 不应为拖动的元素发出选择操作
- 点击或点击应选择一个元素
它适用于其他元素前面的元素,但单击任何其他元素只会将其发送到前面,而无需单击。你能帮我吗?
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/