【发布时间】:2014-05-25 07:13:29
【问题描述】:
有没有办法点击 svg 中的任意位置,让元素捕捉到该位置并同时开始拖动?
我得到的最接近的是下面的代码。拖动圆圈并单击其他位置将使圆圈移动到该位置,但我不知道如何在不释放鼠标并直接单击圆圈的情况下开始拖动。
更一般地说,如何在不直接与被拖动元素交互的情况下启动拖动行为?
var width = 200,
height = 200,
radius = 10;
var drag = d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", function(){
d3.event.sourceEvent.stopPropagation()
})
.on("drag", dragmove);
var svg = d3.select("body")
.data([{x: 100, y : 100}])
.append('svg')
.attr("height", 200)
.attr("widht", 200)
.on("mousedown", function(){
circle.each(dragmove)
});
var circle = svg.append("circle")
.attr("r", radius)
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.call(drag);
function dragmove(d) {
d3.select(this)
.attr("cx", d.x = Math.max(radius, Math.min(width - radius, d3.event.x)))
.attr("cy", d.y = Math.max(radius, Math.min(height - radius, d3.event.y)));
}
【问题讨论】:
-
听起来您希望 SVG 上有一个点击处理程序,可以将圆圈移动到点击的位置。
标签: javascript svg d3.js drag-and-drop