在页面上,我有许多具有相同类的矩形,比如 one
类。
我如何对所有这些矩形应用过渡,以便它们移动到具有新类(可能是类 two
)的新位置,但让那些旧矩形保持静止在同一位置?
如果我解释不正确,有人可以纠正我吗?
例如,我有这些带有“start”类的矩形
d3.select("svg")
.selectAll("rect")
.data([10,20,30,40,50])
.enter()
.append("rect")
.attr("class", "start")
.attr("x", d => d)
.attr("y", 1)
.attr("width", 5)
.attr("height", 5);
这些矩形坐标是(10, 1), (20, 1), (30, 1) ...
然后我移动它们
d3.selectAll("rect")
.transition()
.attr("y", (d, i) => i + 5 * 10);
它们会出现在新的坐标(10, 50), (20, 51), (30, 52) ...
我怎样才能使类 start
在 (10, 1), (20, 1), (30, 1) ... 的原始矩形仍然存在,但有新的在 (10, 50), (20, 51), (30, 52) ... 类 stop
?
最佳答案
正如您在编辑中明确指出的那样,您不想将过渡应用到现有元素:您想要克隆它们并将过渡应用到它们的克隆(或者在将过渡应用到原始元素之前克隆它们,这是相同的...)。
也就是说,D3 有一个非常方便的方法,名为 clone
,其中:
Inserts clones of the selected elements immediately following the selected elements and returns a selection of the newly added clones.
因此,假设您的选择被命名为 rectangles
(建议:始终为您的选择命名),而不是这样做......
rectangles.transition()
.attr("class", "stop")
.attr("y", (d, i) => i + 5 * 10);
...首先克隆它们:
rectangles.each(cloneNodes)
.transition()
.attr("class", "stop")
.attr("y", (d, i) => i + 5 * 10);
function cloneNodes() {
d3.select(this).clone(false);
}
这是演示:
const svg = d3.select("svg");
const rectangles = d3.select("svg")
.selectAll(null)
.data([10, 20, 30, 40, 50])
.enter()
.append("rect")
.attr("class", "start")
.attr("x", d => d)
.attr("y", 1)
.attr("width", 5)
.attr("height", 5);
rectangles.each(cloneNodes)
.transition()
.attr("class", "stop")
.attr("y", (d, i) => i + 5 * 10);
function cloneNodes() {
d3.select(this).clone(false);
}
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>
关于javascript - 在保持旧元素位置的同时应用过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52656952/