我试图找到一种方法来启动mousedown行为时点击的元素,这可能与此类似:
function mousedrag(d){
if(selectedObject == rectangle)
{
...
}
else if(selectedObject == circle){
...
}
else{
...
}
}
请提供帮助,并提前致谢
答案 0 :(得分:1)
在鼠标拖动中使用this.nodeName
:
function mousedrag() {
if (this.nodeName === "circle"){
// it's a circle
} else if (this.nodeName === "rect"){
// it's a rectangle
}
}
完整的工作示例:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
var width = 500,
height = 500,
radius = 20;
var drag = d3.behavior.drag()
// .origin(function(d) { return d; })
.on("drag", dragmove);
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
svg.append("circle")
.attr("r", 20)
.attr("cx", 100)
.attr("cy", 100)
.call(drag);
svg.append("rect")
.attr("width", 30)
.attr("height", 30)
.attr("x", 200)
.attr("y", 200)
.call(drag);
function dragmove() {
if (this.nodeName === "circle"){
d3.select(this)
.attr("cx", d3.event.x)
.attr("cy",d3.event.y);
} else if (this.nodeName === "rect"){
d3.select(this)
.attr("x", d3.event.x)
.attr("y",d3.event.y);
}
}
</script>
</body>
&#13;