animation-direction 合法值仅有 normal、reverse、alternate、alternate-reverse 四个,其他值被忽略并回退为 normal;其仅控制关键帧执行顺序而非空间方向,需配合 animation-iteration-count≥2 或 infinite 才可见交替效果。
只有 normal、reverse、alternate、alternate-reverse 四个有效值,其他如 left、up、backwards 都会被浏览器忽略并回退到 normal。常见错误是误以为它能控制空间方向(比如让元素向左移动),其实它只控制关键帧的执行顺序。
根本原因是没配 animation-iteration-count。当 animation-iteration-count 为 1(默认值)时,即使 animation-direction 是 alternate,也只播一次正向,根本没机会“交替”。
animation-iteration-count 设为 2 或 infinite 才能看到反向帧
alternate:第 1 次正向,第 2 次反向,第 3 次正向……alternate-reverse:第 1 次反向,第 2 次正向,以此类推@keyframes slide {
from { transform: translateX(0); }
to { transform: translateX(100px); }
}
.box {
animation-name: slide;
animation-duration: 1s;
animation-direction: alternate;
animation-iteration-count: infinite; /* 缺它不行 */
}from 和 to 是相对的:它们定义的是单次动画循环的起点和终点,而 animation-direction 决定这个“从→到”的过程是否翻转。例如:
direction: normal → 先应用 from 样式,再过渡到 to 样式direction: reverse → 先应用 to 样式,再过渡到 from 样式(相当于把整个关键帧倒着播)direction: alternate + iteration-count: 2 → 第 1 轮:from→to;第 2 轮:to→from注意:reverse 不等于 “往左走”,而是“把关键帧声明的顺序倒过来执行”。如果你的 from 是 translateX(100px)、to 是 translateX(0),那 normal 反而看起来是向左动。
animation-direction 不决定动画结束后的最终状态,那是 animation-fill-mode 的职责。比如:
direction: reverse,只要 fill-mode: forwards,元素仍会停在 from 关键帧定义的样式上(因为那是反向播放的“终点”)fill-mode: backwards,则动画开始前就应用 to 样式(反向播放的“起点”)容易混淆的点:方向翻转后,“起点”和“终点”的语义互换了,但 fill-mode 依然按关键帧逻辑判断,不是按视觉方向。