关键帧 Animation
约 433 字大约 1 分钟
布欧-Lewyon
2026-05-16
@keyframes 定义多阶段动画,比过渡更强大——控制中间多个状态。
基础用法
@keyframes bounce {
0% { transform: translateY(0); }
50% { transform: translateY(-20px); }
100% { transform: translateY(0); }
}
.element {
animation: bounce 1s ease infinite;
}动画属性
.element {
animation-name: bounce; /* 关键帧名称 */
animation-duration: 1s; /* 时长 */
animation-timing-function: ease; /* 速度曲线 */
animation-delay: 0s; /* 延迟 */
animation-iteration-count: infinite; /* 播放次数(infinite 无限) */
animation-direction: normal; /* 方向:normal / reverse / alternate */
animation-fill-mode: none; /* 填充:none / forwards / backwards / both */
animation-play-state: running; /* 状态:running / paused */
}animation-fill-mode
/* forwards:动画结束后保持最后一帧 */
.element { animation: fadeIn 1s forwards; }
/* backwards:动画延迟期间应用第一帧 */
.element { animation: slideIn 1s 0.5s backwards; }
/* both:forwards + backwards */
.element { animation: fadeIn 1s 0.5s both; }animation-direction
/* alternate → 正向→反向→正向... */
.element { animation: bounce 1s ease infinite alternate; }
/* alternate-reverse → 反向→正向→反向... */
.element { animation: bounce 1s ease infinite alternate-reverse; }关键帧定义
@keyframes slideIn {
from { transform: translateX(-100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
@keyframes rainbow {
0% { background: red; }
25% { background: yellow; }
50% { background: green; }
75% { background: blue; }
100% { background: red; }
}复合动画
一个元素可以同时应用多个动画:
.element {
animation:
bounce 1s ease infinite,
fadeIn 0.5s ease forwards;
}滚动驱动动画
CSS Scroll-driven Animations 让动画进度与滚动位置同步:
@keyframes grow {
from { width: 0%; }
to { width: 100%; }
}
.progress-bar {
animation: grow auto linear;
animation-timeline: scroll(root); /* 以页面滚动驱动 */
}小结
| 属性 | 作用 |
|---|---|
@keyframes | 定义关键帧 |
animation | 简写 |
animation-iteration-count | 播放次数 |
animation-direction | 方向 |
animation-fill-mode | 填充模式 |
animation-play-state | 暂停/恢复 |
上一节:过渡 Transition 下一节:动画性能优化
