如何在SVG组中使2个不同的元素具有不同的拖动行为?

时间:2015-02-19 10:59:47

标签: svg d3.js drag

我在d3.js中有一组2个元素。 javascript代码是:

function onDragDrop(dragHandler, dropHandler) {
var drag = d3.behavior.drag();
drag.on("drag", dragHandler).on("dragstart", startHandler).on("dragend", dropHandler);
return drag;
}
function startHandler(d) {
d3.select('body').style('cursor', 'move');    
d.moveX = d.x;
d.moveY = d.y;
console.log(d.moveX + "," + d.moveY);
}
function dropHandler(d) {
d3.selectAll(".temp").remove();
d3.select('body').style('cursor', 'default');
}
function dragmove(d) {
d.moveX += d3.event.dx;
d.moveY += d3.event.dy;
d.x = Math.round(d.moveX / 50) * 50;
d.y = Math.round(d.moveY / 50) * 50;
d3.select(this).attr("transform", "translate(" + d.x + "," + d.y + ")");
document.getElementById('lblCoord').innerHTML = "[" + (d.x) + "," + (d.y) + "]";
}
function mouseenter(d) {
document.getElementById('lblCoord').innerHTML = "[" + (d.x) + "," + (d.y) + "]";
}
function Otherdragmove(d) {
d.moveX += d3.event.dx;
d.moveY += d3.event.dy;
d3.selectAll(".temp").remove();
d3.selectAll("svg").append("line").attr("x1", d3.event.dx + 60).attr("y1", d3.event.dy + 10).attr("x2", d.moveX).attr("y2", d.moveY).attr("stroke", "black").attr("stroke-width", 2).attr("class", "temp");
}
var DrawCircle = function(container) {
var d = [{ x: 0, y: 0, moveX: 0, moveY: 0 }];
var circle = container.data(d).append("g").attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })//.call(onDragDrop(dragmove, dropHandler)).on("mouseenter", mouseenter);
circle.append("ellipse").attr("cx", 20).attr("cy", 20).attr("rx", 20).attr("ry", 20).attr("stroke", "#FF0000").attr("stroke-width", 1).attr("fill", "#FF0000");
circle.append("ellipse").attr("cx", 60).attr("cy", 20).attr("rx", 20).attr("ry", 20).attr("stroke", "#00FF00").attr("stroke-width", 1).attr("fill", "#00FF00").call(onDragDrop(Otherdragmove, dropHandler));
}
d3.selectAll("svg").remove();
var svgContainer = d3.select("#MainDiv").append("svg").attr("width", 800).attr("height", 600).attr("version", 1.1).attr("xmlns", "http://www.w3.org/2000/svg").attr("viewBox", "-40, -40, 1600, 1200");
DrawCircle(svgContainer);

我在这里创造了一个小提琴:http://jsfiddle.net/oqu8j072/6/

我想要它,这样如果我点击并拖动红色圆圈,就可以移动2个圆圈组。我也希望如果我点击并拖动绿色圆圈,应该会发生不同的动作,在这个例子中它画了一条线。

我无法在同一个实例中发生这两件事。

如代码所示,它会生成从绿色圆圈拖动的线条。如果我取消注释此行上的代码:

var circle = container.data(d).append("g").attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })//.call(onDragDrop(dragmove, dropHandler)).on("mouseenter", mouseenter);

然后点击并拖动两个圆圈中的任何一个都会移动它们。

如何才能达到我想要的效果?

1 个答案:

答案 0 :(得分:1)

解决方案只是非常少的额外代码。

在启动处理程序中只需输入以下行:

d3.event.sourceEvent.stopPropagation(); 

我有一个小提琴:

http://fiddle.jshell.net/Lytuno8y/1/