![](/img/trans.png)
[英](D3) dispatching “mousedown” event to selection with drag behaviour throws error
[英]D3 Triggering drag during mousedown
有没有办法单击 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 画布中添加了 mousedown、mousemove 和 mouseup 处理程序。 这是我想要的功能,但我仍然更喜欢使用 d3 的拖动行为。 如果有人有更优雅的解决方案,请告诉我。
var width = 200,
height = 200,
radius = 10;
var isDown = false;
var svg = d3.select("body")
.data([{x: 100, y : 100}])
.append('svg')
.attr("height", 200)
.attr("width", 200)
.on("mousedown", function(){
isDown = true;
var coordinates = d3.mouse(this);
circle.each(function(d){
circle.attr("cx", d.x = coordinates[0])
circle.attr("cy", d.y = coordinates[1])
})
})
.on("mousemove", function(){
if(isDown) {
var coordinates = d3.mouse(this);
circle.each(function(d){
circle.attr("cx", d.x = coordinates[0])
circle.attr("cy", d.y = coordinates[1])
})
}
})
.on("mouseup", function(){
isDown = false;
});
var circle = svg.append("circle")
.attr("r", radius)
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.