我正在从这里http://ssun.azurewebsites.net/creating-a-draggable-object-in-d3/玩一个很棒的教程。我在理解通过调用等功能传递的内容时遇到问题。例如,如何选择两个圆圈之一。修改后的代码如下:
<!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>
如您所见,只有一个被选中,另一个消失了。如何参考特定的圈子?在编写用于调用的匿名函数时,如何发现它们传递了哪些参数?
谢谢大家!
最佳答案
处理程序应使用以下命令访问目标节点
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>
关于javascript - 拖动多个圈子之一,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43823983/