2015-10-18 97 views
0

我試圖找到一種方式來獲得被點擊時,鼠標按下的行爲發起了什麼元素點擊的元素,東西可以的工作方式類似於此:檢測上的mousedown

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

請幫忙,在此先感謝

+0

'selectedObj'將'd.target' – MinusFour

+0

@MinusFour所以d.target ==圈會的工作?那麼類怎麼樣? – gamehen

+0

這將取決於「circle」是什麼,你想要什麼。你想檢查'd.target'是否是圓形或矩形的**實例**? – MinusFour

回答

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>