这个问题与以下问题密切相关:
在那个问题中,组中有一个单独的g元素和一堆svg元素。解决方案是在dragstart上使用d3.event.sourceEvent.stopPropagation。
就我而言,我有一个带有一堆svg元素的g元素,包括其他g元素。这是我创建的一个简单示例,用于说明我的问题:http://jsfiddle.net/eforgy/x1cwur41/(下面复制的代码)。
小提琴创建三个嵌套的g元素,每个g元素只包含一个rect。如果你打开一个控制台并单击最里面的红色矩形,尽管在dragstart上有一个stopPropagation,你可以看到它似乎从顶部红色矩形传播到底部蓝色矩形,当你开始拖动时,它正在使用拖动蓝色矩形,即所有三个移动。我试图产生的行为如下:
任何帮助都将不胜感激。
PS:这是代码:
var child = {index: 0};
var w = 800,
h = 600;
var svg = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h);
var cinit = function() {
return svg;
};
cinit.x = 0;
cinit.y = 0;
cinit.width = w;
cinit.height = h;
var c0 = new Component(cinit); c0.fill = "blue";
var c1 = new Component(c0); c1.fill = "green";
var c2 = new Component(c1); c2.fill = "red";
function Component(parent) {
var id = child.index;
child.index += 1;
console.log("Created component "+id);
var x = 1.1*parent.x;
var y = 1.1*parent.y;
var width = .5*parent.width;
var height = .5*parent.height;
var fill = "blue";
var stroke = "black";
var drag = d3.behavior.drag()
.origin(function() {
var t = d3.transform(group.attr("transform")).translate;
return {
x: t[0],
y: t[1]
};
})
.on("drag", function() {
console.log("drag: "+id);
var p = component.position;
p[0] = d3.event.x;
p[1] = d3.event.y;
component.position = p;
})
.on("dragstart", function() {
console.log("dragstart: "+id);
d3.event.sourceEvent.stopPropagation;
});
var group = parent().append("g")
.attr("transform", "translate("+x+","+y+")")
.call(drag);
var rect = group.append("rect")
.attr("width", width)
.attr("height", height)
.attr("fill", fill)
.attr("stroke", stroke)
.on("click", function() {console.log("Clicked "+id);});
function component() {
return group;
};
Object.defineProperty(component,"position",{
get: function() {return [x, y, width, height];},
set: function(_) {
x = _[0];
y = _[1];
width = _[2];
height = _[3];
rect.attr("width", width).attr("height", height);
group.attr("transform", "translate("+x+","+y+")");
return component;
}
});
Object.defineProperty(component,"x",{
get: function() {return x;},
set: function(_) {
x = _;
group.attr("transform", "translate("+x+","+y+")");
return component;
}
});
Object.defineProperty(component,"y",{
get: function() {return y;},
set: function(_) {
y = _;
group.attr("transform", "translate("+x+","+y+")");
return component;
}
});
Object.defineProperty(component,"width",{
get: function() {return width;},
set: function(_) {
width = _;
rect.attr("width", width).attr("height", height);
return component;
}
});
Object.defineProperty(component,"height",{
get: function() {return height;},
set: function(_) {
height = _;
rect.attr("width", width).attr("height", height);
return component;
}
});
Object.defineProperty(component,"fill",{
get: function() {return fill;},
set: function(_) {
fill = _;
rect.attr("fill", fill);
return component;
}
});
return component;
}
答案 0 :(得分:0)
问题是你没有调用函数d3.event.sourceEvent.stopPropagation
。你最后错过了括号()
。
如有疑问,请不要忘记查看D3 documentation;)