如何复用CSS关键帧动画,让多元素从不同帧位置启动执行
实现方案
你可以通过CSS的animation-delay负值属性实现需求,完全不需要编写多套动画关键帧,一套即可复用。
原有代码需要先补全父容器的定位属性,避免子元素绝对定位相对于视口偏移:
.parent { background-color: aliceblue; height: 400px; width: 400px; margin: 25px; padding: 25px; position: relative; /* 新增,子元素将相对于父容器定位 */ } .child{ background: black; position: absolute; height:100px; width:100px; animation: move_around 5s ease-in-out infinite backwards; } /* 4个方块分别配置对应负延迟,直接从指定动画进度启动 */ .child:nth-child(2) { animation-delay: -1.25s; } .child:nth-child(3) { animation-delay: -2.5s; } .child:nth-child(4) { animation-delay: -3.75s; } @keyframes move_around { 0% { transform: translateX(0%); } 25% { transform: translateY(300%); } 50% { transform: translateY(300%) translateX(300%); } 75% { transform: translateX(300%); } /* 补全100%关键帧,保证动画循环衔接自然 */ 100% { transform: translateX(0%); } }
HTML代码直接添加4个相同的子元素即可:
<div class="parent"> <div class='child'></div> <div class='child'></div> <div class='child'></div> <div class='child'></div> </div>
实现逻辑
- 动画总时长为5s,负值的
animation-delay会让浏览器直接跳过对应时长的等待阶段,从该时间点对应的动画状态开始播放,正好匹配你需要的「提前N%关键帧进度启动」的需求。 - 示例中4个方块分别设置0s、-1.25s(50.25)、-2.5s(50.5)、-3.75s(5*0.75)的延迟,正好对应四个角的初始位置,无需额外编写关键帧。
- 如果后续需要新增更多方块,只需按照
- 动画总时长 * 起始进度百分比的规则计算对应延迟值即可,复用性极强。
内容的提问来源于stack exchange,提问作者Mitchell van Zuylen
相关产品推荐
相关产品推荐

