animation-direction CSS 属性设置动画是应正向播放、反向播放还是在正向和反向之间交替播放。

{{InteractiveExample("CSS Demo: animation-direction")}}

```css interactive-example-choice animation-direction: normal;


```css interactive-example-choice animation-direction: reverse;

```css interactive-example-choice animation-direction: alternate;


```css interactive-example-choice animation-direction: alternate-reverse;

```html interactive-example


```css interactive-example #example-element { animation-duration: 3s; animation-iteration-count: infinite; animation-name: slide; animation-play-state: paused; animation-timing-function: ease-in; background-color: #1766aa; border-radius: 50%; border: 5px solid #333; color: white; height: 150px; margin: auto; margin-left: 0; width: 150px; } #example-element.running { animation-play-state: running; } #play-pause { font-size: 2rem; } @keyframes slide { from { background-color: orange; color: black; margin-left: 0; } to { background-color: orange; color: black; margin-left: 80%; } }

```js interactive-example "use strict";

window.addEventListener("load", () => { const el = document.getElementById("example-element"); const button = document.getElementById("play-pause");

button.addEventListener("click", () => { if (el.classList.contains("running")) { el.classList.remove("running"); button.textContent = "Play"; } else { el.classList.add("running"); button.textContent = "Pause"; } }); });


使用 {{cssxref("animation")}} 的简写属性通常非常方便,可以一次性设置所有动画属性。 ## 语法 ```css /* 单个动画 */ animation-direction: normal; animation-direction: reverse; animation-direction: alternate; animation-direction: alternate-reverse; /* 多个动画 */ animation-direction: normal, reverse; animation-direction: alternate, reverse, normal; /* 全局值 */ animation-direction: inherit; animation-direction: initial; animation-direction: revert; animation-direction: revert-layer; animation-direction: unset;

  • normal
    • : 动画在每个循环中正向播放。换句话说,每次动画循环时,动画将重置为起始状态并重新开始。这是默认值。
  • reverse
    • : 动画在每个循环中反向播放。换句话说,每次动画循环时,动画将重置为结束状态并重新开始。动画步骤将反向执行,并且时间函数也将被反转。例如,ease-in 时间函数变为 ease-out
  • alternate
    • : 动画在每个循环中正反交替播放,第一次迭代是正向播放。确定循环是奇数还是偶数的计数从 1 开始。
  • alternate-reverse
    • : 动画在每个循环中正反交替播放,第一次迭代是反向播放。确定循环是奇数还是偶数的计数从 1 开始。

[!NOTE] 当你在 animation-* 属性上指定多个逗号分隔的值时,它们将按照 {{cssxref("animation-name")}} 出现的顺序应用于动画。对于动画数量和 animation-* 属性值不匹配的情况,请参见设置多个动画属性值

形式定义

{{cssinfo}}

形式语法

{{csssyntax}}

示例

反转动画方向

HTML

<div class="box"></div>

CSS

.box {
  background-color: rebeccapurple;
  border-radius: 10px;
  width: 100px;
  height: 100px;
}

.box:hover {
  animation-name: rotate;
  animation-duration: 0.7s;
  animation-direction: reverse;
}

@keyframes rotate {
  0% {
    transform: rotate(0);
  }
  100% {
    transform: rotate(360deg);
  }
}

结果

{{EmbedLiveSample("反转动画方向","100%","250")}}

参见 CSS 动画以获取示例。