我正在玩这里的精彩教程http://ssun.azurewebsites.net/creating-a-draggable-object-in-d3/。我在理解通过call等函数传递的内容时遇到了问题。例如,我如何选择两个圆圈中的一个。修改后的代码如下:
<!DOCTYPE html>
<html>
<head>
<!-- Load D3 from site -->
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<!-- End CSS (Styling) -->
</head>
<body>
<h3></h3>
<!-- Begin D3 Javascript -->
<script type="text/javascript">
var boxWidth = 600;
var boxHeight = 400;
var box = d3.select('body')
.append('svg')
.attr('class', 'box')
.attr('width', boxWidth)
.attr('height', boxHeight);
var drag = d3.behavior.drag()
.on('dragstart', function() { circle.style('fill', 'red'); })
.on('drag', function() { circle.attr('cx', d3.event.x)
.attr('cy', d3.event.y); })
.on('dragend', function() { circle.style('fill', 'black'); });
var circle = box.selectAll('.draggableCircle')
.data([{ x: (boxWidth / 3), y: (boxHeight / 3), r: 25 },{ x: (boxWidth / 2), y: (boxHeight / 2), r: 25 }])
.enter()
.append('circle')
.attr('class', 'draggableCircle')
.attr('cx', function(d) { return d.x; })
.attr('cy', function(d) { return d.y; })
.attr('r', function(d) { return d.r; })
.call(drag)
.style('fill', 'black');
</script>
</body>
</html>
如您所见,只有一个被选中而另一个被消失。如何引用特定的圆圈?在为呼叫编写匿名函数时,如何发现它们传递的参数?
提前谢谢大家!
答案 0 :(得分:1)
您的处理程序应使用
访问目标节点d3.select(this)
而不是circle.
<!DOCTYPE html>
<html>
<head>
<!-- Load D3 from site -->
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<!-- End CSS (Styling) -->
</head>
<body>
<h3></h3>
<!-- Begin D3 Javascript -->
<script type="text/javascript">
var boxWidth = 600;
var boxHeight = 400;
var box = d3.select('body')
.append('svg')
.attr('class', 'box')
.attr('width', boxWidth)
.attr('height', boxHeight);
var drag = d3.behavior.drag()
.on('dragstart', function(c) { d3.select(this).style('fill', 'red'); })
.on('drag', function(c) { d3.select(this).attr('cx', d3.event.x)
.attr('cy', d3.event.y); })
.on('dragend', function(c) { d3.select(this).style('fill', 'black'); });
var circle = box.selectAll('.draggableCircle')
.data([{ x: (boxWidth / 3), y: (boxHeight / 3), r: 25 },{ x: (boxWidth / 2), y: (boxHeight / 2), r: 25 }])
.enter()
.append('circle')
.attr('class', 'draggableCircle')
.attr('cx', function(d) { return d.x; })
.attr('cy', function(d) { return d.y; })
.attr('r', function(d) { return d.r; })
.call(drag)
.style('fill', 'black');
</script>
</body>
</html>
&#13;