CSS 关键帧动画深入
学习@keyframes · 难度:进阶 · +15XP
CSS 关键帧动画深入
CSS @keyframes 动画相比 transition 提供了更强大的控制能力,支持多阶段、循环、反向播放等复杂动画效果。本教程深入讲解高级动画技巧。
@keyframes 语法回顾
@keyframes 动画名称 {
0% { /* 起始状态 */ }
50% { /* 中间状态 */ }
100% { /* 结束状态 */ }
}
.element {
animation: 动画名称 持续时间 缓动函数 延迟 次数 方向 填充模式;
}
animation 子属性全解
| 属性 | 说明 | 常用值 |
|---|---|---|
animation-name | 动画名称 | 自定义名称或 none |
animation-duration | 持续时间 | 2s, 500ms |
animation-timing-function | 缓动曲线 | ease, linear, cubic-bezier() |
animation-delay | 延迟时间 | 0s, 1s(负值可跳过开头) |
animation-iteration-count | 播放次数 | 1, 3, infinite |
animation-direction | 播放方向 | normal, reverse, alternate |
animation-fill-mode | 填充模式 | none, forwards, backwards, both |
animation-play-state | 播放状态 | running, paused |
animation-direction 详解
/* alternate — 来回播放 */
.pendulum {
animation: swing 1s ease-in-out infinite alternate;
}
@keyframes swing {
from { transform: rotate(-15deg); }
to { transform: rotate(15deg); }
}
animation-fill-mode 详解
/* forwards — 保持动画结束状态 */
.fade-in-stay {
animation: fadeIn 0.5s ease forwards;
/* 动画结束后保持 opacity: 1 */
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
贝塞尔曲线自定义缓动
/* 自定义缓动 — 弹跳效果 */
.bounce {
animation: bounce 2s cubic-bezier(0.68, -0.55, 0.27, 1.55) infinite;
}
/* steps() — 逐帧动画 */
.sprite {
animation: sprite 1s steps(8) infinite;
/* 分 8 步播放,每步一帧 */
}
多动画同时播放
.combined {
animation:
slideIn 1s ease-out,
fadeIn 0.8s ease,
pulse 2s ease 1s infinite;
}
动画暂停与恢复
.card {
animation: float 3s ease-in-out infinite;
}
.card:hover {
animation-play-state: paused; /* 悬停时暂停 */
}
高性能动画属性
以下属性的动画由 GPU 加速,不会引起重排(reflow):
transform(位移、旋转、缩放、倾斜)opacity(透明度)filter(滤镜,部分场景)
/* 推荐 — GPU 加速 */
@keyframes slideUp {
from { transform: translateY(50px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
/* 避免 — 触发重排 */
@keyframes badAnimation {
from { top: 50px; width: 100px; } /* 触发回流 */
to { top: 0; width: 300px; }
}
复杂动画实例 — 加载动画
@keyframes spin {
to { transform: rotate(360deg); }
}
@keyframes dash {
0% { stroke-dasharray: 1, 150; stroke-dashoffset: 0; }
50% { stroke-dasharray: 90, 150; stroke-dashoffset: -35; }
100% { stroke-dasharray: 90, 150; stroke-dashoffset: -124; }
}
.spinner {
animation: spin 2s linear infinite;
}
.spinner circle {
animation: dash 1.5s ease-in-out infinite;
}
动画事件(JavaScript)
可以用 JS 监听动画的animationstart、animationend和animationiteration事件,在关键时刻执行逻辑。
CSS 动画不仅用于装饰,更是现代 Web 交互体验的核心。熟练运用关键帧动画能让你创建出流畅、自然、令人愉悦的用户界面。