gpt4 book ai didi

javascript - 拖动多个圆圈之一

转载 作者:行者123 更新时间:2023-12-03 04:23:44 26 4
gpt4 key购买 nike

我正在研究这里的一个很棒的教程 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>

如您所见,仅选择了一个,另一个消失了。如何引用特定的圈子?在编写用于调用的匿名函数时,如何发现它们传递的参数?

先谢谢大家了!

最佳答案

您的处理程序应使用访问目标节点

d3.select(this)

而不是圆圈。

<!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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com