我正在尝试在下面堆叠 CSS 关键帧(动画延迟),但我不确定如何以编程方式执行此操作?
.r1 {
animation-name: move1;
animation-delay: 0.5s;
animation-duration: 1s;
animation-iteration-count: 1;
animation-timing-function: ease-in;
animation-direction: normal;
animation-fill-mode: forwards;
}
.r2 {
animation-name: move1;
animation-delay: 1.5s;
animation-duration: 1s;
animation-iteration-count: 1;
animation-timing-function: ease-in;
animation-direction: normal;
animation-fill-mode: forwards;
}
.r3 {
animation-name: move1;
animation-delay: 2.5s;
animation-duration: 1s;
animation-iteration-count: 1;
animation-timing-function: ease-in;
animation-direction: normal;
animation-fill-mode: forwards;
}
@keyframes move1 {
to {
transform: translateX(200px);
}
}
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">
<rect class="r1" x="10" y="20" width="100" height="100" fill="red"/>
<rect class="r2" x="10" y="130" width="100" height="100" fill="green"/>
<rect class="r3" x="10" y="240" width="100" height="100" fill="blue"/>
</svg>
animation-duration
为每个类和 animation-delay
进行了硬编码被硬编码为头等舱,即 r1
.
如何传递r2和r3的延迟,比如
r2 delay= r1 delay + r1 duration->0.5+1=1.5s
和
r3 delay= r2 delay + r2 duration ->1.5+1=2.5s
在 javascript 中有没有给出 animation-duration
的东西?按类(class)?
我尝试通过 Element.getAnimations() 做到这一点但我不确定是否有任何东西可以按类提供动画持续时间。
我不想手动执行此操作,因为我在 svg 中有很多类。
提前谢谢你。
最佳答案
为你的 rects 设置 r 类,我认为这可以帮助你:
const blocks = document.querySelectorAll('svg rect');
for (let i = 1; i<blocks.length; i++) {
const element = blocks[i];
const prevElementStyles = getComputedStyle(blocks[i-1]);
element.style.animationDelay = `${parseFloat(prevElementStyles.animationDelay) + parseFloat(prevElementStyles.animationDuration)}s`;
}
r类:
.r {
animation-name: move1;
animation-delay: 0.5s;
animation-duration: 1s;
animation-iteration-count: 1;
animation-timing-function: ease-in;
animation-direction: normal;
animation-fill-mode: forwards;
}
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">
<rect class="r" x="10" y="20" width="100" height="100" fill="red"/>
<rect class="r" x="10" y="130" width="100" height="100" fill="green"/>
<rect class="r" x="10" y="240" width="100" height="100" fill="blue"/>
</svg>
关于javascript - 如何以编程方式在 CSS 动画中堆叠关键帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70900961/