CSS关键帧序列动画异常:5个方块反向循环
解决5个方块依次弹跳动画反向循环的问题
问题说明
需求:实现5个方块依次执行弹跳动画,完成一轮后从头开始正向循环。
当前问题:动画执行完一轮后会反向重启,无法按预期正向循环。
原有设置:总动画时长8秒,每个方块分配2秒动画区间,已为每个方块定义独立的@keyframes bounce1至bounce5。
原因分析
问题核心在于动画属性中的alternate关键字——这个属性会让动画在每次循环时反向播放,导致一轮正向动画结束后,会倒着执行一遍动画,看起来像是反向重启。另外,原有代码为每个方块编写独立关键帧的方式冗余,其实可以通过延迟设置实现更简洁的效果。
解决方案
- 移除所有动画的
alternate参数,保持默认的normal循环方向(或显式声明),确保每次循环都是正向执行。 - 合并所有独立的
@keyframes为一个通用弹跳关键帧,每个方块通过animation-delay控制触发时间,实现依次弹跳的效果。 - 调整关键帧时间点,让弹跳动作在20%的时长内完成(对应总时长8秒中的2秒),剩余时间保持静止。
修改后的代码
CSS代码
/* 通用弹跳关键帧:0-20%区间完成一次弹跳,剩余时间保持静止 */ @keyframes bounce { 0%, 20%, 100% { transform: translateY(0); } 10% { transform: translateY(var(--bounce-height)); } } body { height: 300px; display: flex; justify-content: center; align-items: center; gap: 16px; } .box { width: 60px; height: 60px; background: var(--bg); border-radius: 4px; will-change: transform; --bounce-height: -20px; --animation-duration: 8000ms; } @media (prefers-reduced-motion: no-preference) { .box { animation: bounce var(--animation-duration) infinite cubic-bezier(.2, .65, .6, 1); } /* 为每个方块设置依次延迟,实现轮流弹跳 */ .one { animation-delay: 0s; } .two { animation-delay: 2s; } .three { animation-delay: 4s; } .four { animation-delay: 6s; } .five { animation-delay: 8s; } } /* 方块背景色变量 */ .box.one { --bg: slateblue; } .box.two { --bg: deeppink; } .box.three { --bg: dodgerblue; } .box.four { --bg: red; } .box.five { --bg: yellow; }
HTML代码
<div class="box one"></div> <div class="box two"></div> <div class="box three"></div> <div class="box four"></div> <div class="box five"></div>
逻辑说明
- 通用关键帧
bounce定义了0-20%区间内完成一次完整弹跳(初始位置→弹起→回到原位),剩下的80%时间保持静止,刚好对应总时长8秒中的2秒动画、6秒静止。 - 每个方块通过
animation-delay依次延迟2秒(总时长的20%),第一个方块0秒启动,第二个2秒启动,直到第五个8秒启动,刚好在第一个方块完成一轮时,第五个开始,形成连续的依次弹跳循环。 - 移除
alternate后,动画每次循环都正向执行,彻底解决反向重启的问题。
内容的提问来源于stack exchange,提问作者bengaltiger
相关产品推荐
相关产品推荐

