![](/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.