steps()函数通过将动画分解为离散步进实现帧动画效果,常用于精灵图、打字机、计数器等场景,配合background-position精确控制每帧显示,相比连续时间函数更具节奏感与性能优势。

steps()
使用
steps()
animation-timing-function
steps(number_of_steps, [start | end])
number_of_steps
start | end
end
end
start
让我们通过一个经典的精灵图动画例子来具体说明:
假设我们有一个横向排列的精灵图,包含了5帧动画,每帧宽度是100px。
立即学习“前端免费学习笔记(深入)”;
HTML:
<div class="sprite-animation"></div>
CSS:
.sprite-animation {
width: 100px; /* 单帧宽度 */
height: 100px; /* 单帧高度 */
background-image: url('your-sprite-sheet.png'); /* 你的精灵图路径 */
background-repeat: no-repeat;
/* 精灵图总宽度为 5帧 * 100px/帧 = 500px */
/* 动画总时长 */
animation: playSprite 1s steps(5) infinite; /* 1秒完成5步,无限循环 */
}
@keyframes playSprite {
from {
background-position: 0 0; /* 从第一帧开始 */
}
to {
/* 移动到显示最后一张帧的下一个位置,
这样 steps(5) 才能在5步中完整显示 0, -100px, -200px, -300px, -400px 这5个位置 */
background-position: -500px 0;
}
}在这个例子中:
animation: playSprite 1s steps(5) infinite;
playSprite
infinite
@keyframes playSprite
from { background-position: 0 0; }to { background-position: -500px 0; }to
background-position
-(N * W)px 0
steps(N)
W
steps(5)
0px
-500px
end
0px
-100px
-200px
-300px
-400px
-500px
0px
steps()
linear
ease
steps()
linear
ease
cubic-bezier
linear
ease
cubic-bezier
ease-in-out
而
steps()
start
end
从用途上讲:
linear
ease
steps()
我个人觉得,很多时候我们潜意识里总想把所有动画都做得“丝滑”,但其实
steps()
steps()
要用
steps()
steps()
精心准备精灵图(Sprite Sheet):
精确计算background-position
N
W
@keyframes
from
background-position: 0 0;
to
background-position: -(N * W)px 0;
-(总帧数 * 单帧宽度)
-(总帧数 - 1 * 单帧宽度)
-(N * W)px
steps(N)
0
-(N * W)px
N
end
0
-W
-2W
-(N-1)W
to
-(N-1)W
animation-duration
number_of_steps
animation-duration
number_of_steps
animation-duration / number_of_steps
animation-duration
animation-fill-mode
animation-fill-mode: forwards;
animation-iteration-count: infinite;
forwards
理解start
end
steps(N, end)
steps(N, start)
steps(N, start)
@keyframes
to
-( (N-1) * W )px
number_of_steps
N+1
to
-(N * W)px
end
我遇到过不少人,包括我自己,在刚开始使用
steps()
number_of_steps
to
background-position
start
end
steps(N)
N
background-position
0
-(N * W)px
steps()
steps()
进阶应用场景:
打字机效果(Typewriter Effect):
width
clip-path
steps()
span
width: 0; overflow: hidden;
width
animation-timing-function: steps(字符数量, end);
数字计数器/加载进度条:
steps()
transform: translateY()
steps(10)
steps()
自定义加载动画(Loading Spinners):
steps()
steps()
游戏UI和特效:
steps()
steps()
性能考量:
steps()
transform
opacity
steps()
animation-timing-function
steps()
background-position
src
steps()
steps()
steps()
background-position
width
height
我个人经验是,当需要实现帧动画时,
steps()
steps()
以上就是CSS中如何使用steps()函数?通过steps()控制动画的步进效果以实现帧动画的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号