🎬 一、animation 是什么?
CSS3 中的 animation 用来给元素添加关键帧动画,能让元素在指定时间内自动完成一系列变换(移动、旋转、透明度等等)。
🧩 二、animation 的常用属性(共 8 个)
| 属性名 | 作用 | 示例 | 默认值 |
|---|---|---|---|
🎞️ animation-name |
指定关键帧动画名称 | animation-name: fadeIn; |
none |
🕒 animation-duration |
动画持续时间 | animation-duration: 2s; |
0s |
🕹️ animation-timing-function |
动画节奏曲线 | animation-timing-function: ease-in-out; |
ease |
🔁 animation-iteration-count |
动画播放次数 | animation-iteration-count: infinite; |
1 |
↔️ animation-direction |
播放方向(正向/反向/来回) | animation-direction: alternate; |
normal |
⏱️ animation-delay |
延迟开始时间 | animation-delay: 1s; |
0s |
⏹️ animation-fill-mode |
动画开始/结束时状态是否保留 | animation-fill-mode: forwards; |
none |
✅ animation-play-state |
动画播放或暂停 | animation-play-state: paused; |
running |
🧪 三、关键帧 @keyframes
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
🔧 你也可以用百分比:
@keyframes slide {
0% { transform: translateX(0); }
50% { transform: translateX(100px); }
100% { transform: translateX(0); }
}
💡 四、animation 简写格式:
animation: name duration timing-function delay iteration-count direction fill-mode play-state;
🧾 示例:
.my-box {
animation: fadeIn 2s ease-in-out 0.5s infinite alternate forwards running;
}
🔍 五、常见组合案例
1. 🚶 简单的移动动画
@keyframes move {
from { transform: translateX(0); }
to { transform: translateX(100px); }
}
.box {
animation: move 1s linear infinite alternate;
}
2. 🛑 停留在最后状态
animation-fill-mode: forwards;
3. ⏸️ 动画暂停
animation-play-state: paused;
可以配合 JavaScript 控制:
document.querySelector('.box').style.animationPlayState = 'paused';
✅ 六、小贴士
-
多个动画用逗号
,分隔:
animation: move 2s ease, fadeIn 1s ease-in-out;
-
动画可与 hover、focus 等伪类搭配使用。