gpt4 book ai didi

javascript - D3 - 跨组拖动多个元素

转载 作者:行者123 更新时间:2023-12-03 02:32:34 24 4
gpt4 key购买 nike

我正在尝试实现 D3 拖动行为,但我没有找到示例。

下面的代码创建了几行,每行都有一个矩形、圆形和椭圆形,并且为圆形启用了拖动功能。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Drag many</title>
<style media="screen">
.active {
stroke: #000;
stroke-width: 2px;
}
</style>
</head>
<body>
<svg width=1000 height=500></svg>

<script src="https://d3js.org/d3.v4.min.js" charset="utf-8"></script>
<script type="text/javascript">
var svg=d3.select("svg"),
mainGroup = svg.append("g");

var squareData = [
{x:25, y:23, width:15, height:15},
{x:25, y:63, width:15, height:15}
];

var circleData = [
{cx:60, cy:30, r:10},
{cx:60, cy:70, r:10}
];

var ellipseData = [
{cx:90, cy:30, rx:10, ry:15},
{cx:90, cy:70, rx:10, ry:15}
];

var squareGroup = mainGroup.append("g");
squareGroup.selectAll(null)
.data(squareData)
.enter().append("rect")
.attr("class", (d,i)=>`rectGroup row_${i+1}`)
.attr("x", d=>d.x)
.attr("y", d=>d.y)
.attr("width", d=>d.width)
.attr("height", d=>d.height)
.attr("fill", "blue");

circleGroup = mainGroup.append("g");
circleGroup.selectAll(null)
.data(circleData)
.enter().append("circle")
.attr("class", (d,i)=>`circleGroup row_${i+1}`)
.attr("cx", d=>d.cx)
.attr("cy", d=>d.cy)
.attr("r", d=>d.r)
.attr("fill", "red")
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));

ellipseGroup = mainGroup.append("g");
ellipseGroup.selectAll(null)
.data(ellipseData)
.enter().append("ellipse")
.attr("class", (d,i)=>`ellipseGroup row_${i+1}`)
.attr("cx", d=>d.cx)
.attr("cy", d=>d.cy)
.attr("rx", d=>d.rx)
.attr("ry", d=>d.ry)
.attr("fill", "green");

function dragstarted(d){
d3.select(this).classed("active", true);
}

function dragended(d){
d3.select(this).classed("active", false);
}

function dragged(d){
//var dx = d3.event.x - d3.select(this).attr("cx")
d3.select(this).attr("cx", d.x = d3.event.x);
// I really need to move all the elements in this row here,
// with the circle being the pivot...
}


</script>
</body>
</html>

我想修改圆圈的拖动行为,以拉动整行而不是单独移动。

我怎样才能实现这个目标?

最佳答案

看起来你给每一行一个类,而不是:

函数拖拽(d){d3.select(this).attr("cx", d.x = d3.event.x);}

获取该行的类(从代码的外观来看,它应该是第二类):var thisRow = d3.select(this).attr("class").split()[1 ];

.split() 将按空格分割,这就是获取类列表将吐出其结果的方式。

获得类(class)后,移动该类(class)的所有内容:

d3.selectAll("."+ thisRow).attr("cx", d.x = d3.event.x);

关于javascript - D3 - 跨组拖动多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48672972/

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