【发布时间】:2015-02-10 16:12:04
【问题描述】:
在我的 svg 容器中,我有一个带有矩形和文本的 <g>。拖动这个组时,我想让组消失,只需在屏幕上拖动一个小矩形来表示对象。为了做到这一点,我使用了<div>,在拖动开始时我可以看到它。我让被拖动的 svg 组消失了。
你可以看到小提琴here。 代码在这里:
function dragDiv2End(d) {
console.log('ending');
var a = d3.select(this);
a.attr('x', initial.x).attr('y', initial.y).attr('width', initial.width).attr('height', initial.height);
a.transition().style("opacity",1);
d3.select('#dragid').style('visibility', 'hidden');
}
function dragDiv2Start(d) {
d3.event.sourceEvent.stopPropagation();
console.log('starting');
var a = d3.select(this);
initial = {x: a.attr('x'), y: a.attr('y'), width: a.attr('width'), height: a.attr('height')};
a.attr('x', d3.mouse(this)[0])
.attr('y', d3.mouse(this)[1]) .attr('width', 20)
.attr('height', 20).style("opacity",0);
var b = d3.select('#dragid');
b.style({
left: (parseInt(d3.mouse(this)[0])) + "px",
top: d3.mouse(this)[1] + "px",
border: "1px solid black",
visibility: 'visible'
});
}
function dragDiv2Move(d) {
var b = d3.select(this);
var a = d3.select('#dragid');
a.transition().delay(50).style('opacity', 1);
//console.log(d3.event.x, d3.event.y, a.style("right"));
console.log(d3.mouse(this));
a.style({
left: (parseInt(d3.mouse(this)[0])) + "px",
top: d3.mouse(this)[1] + "px"
});
}
function doClick(d) {
if (d3.event.defaultPrevented) return;
console.log('clicked');
}
var initial = {};
var svg = d3.select('#div2').append('svg').attr('height', 300).attr('width', 300).style('border', 'solid 1px blue');
var g = svg.append('g').on('click', doClick);
g.append('rect').attr('x', 10).attr('y', 10).attr('width', 200).attr('height', 200).style('stroke', 'red').style('fill', 'white');
var text = g.append('text')
text.text('my test').attr('x', 50).attr('y', 50);
var dragDiv = d3.behavior.drag()
.origin(Object)
.on("drag", dragDivMove);
var dragDiv2 = d3.behavior.drag()
.origin(Object)
.on("dragstart", dragDiv2Start)
.on("drag", dragDiv2Move)
.on("dragend", dragDiv2End);
g.call(dragDiv2);
问题始于组也应该监听的点击事件。当一个简单的点击发生时,我得到了我的 svg 对象消失的闪烁效果(拖动事件的行为)。
我明白为什么会发生这种情况,但这是非常不可取的,我正在努力寻找解决这个问题的方法。要查看它的发生,只需单击和/或拖动红色矩形。
我尝试阻止事件传播,从拖动到单击都可以正常工作,但反之则不行。
任何建议将不胜感激。
【问题讨论】:
-
您必须在
dragDiv2Start函数中添加一些条件逻辑,以限制视觉变化,直到某种阈值变为真......无论是某种距离还是时间。 -
这是一个非常简洁的解决方案。效果很好
标签: javascript svg d3.js drag-and-drop