我正在尝试找到一种方法来获取在启动mousedown行为时单击的元素,这种方法可能与此类似:

function mousedrag(d){
    if(selectedObject == rectangle)
    {
        ...
    }
    else if(selectedObject == circle){
        ...
    }
    else{
        ...
    }
}


请帮助,并在此先感谢

最佳答案

在鼠标拖动中使用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>

10-07 18:43