CSS3 animation-iteration-count 属性


CSS3 animation-iteration-count 属性

CSS3 animation-iteration-count 属性用于控制CSS动画的循环次数。通过设置该属性的值,可以确定动画循环的次数,从而控制动画播放的次数。

语法

animation-iteration-count: number | infinite | initial | inherit;

其中,

  • number:表示动画循环的次数,可以为整数或小数。
  • infinite:表示动画将无限循环。
  • initial:表示将属性设置为默认值。
  • inherit:表示从父元素继承该属性。

注意,该属性定义在 keyframes 语句中会覆盖 animation 属性中设置的循环次数。

使用示例

设置动画只播放一次

div {
  animation-name: example;
  animation-duration: 2s;
  animation-iteration-count: 1;
}

@keyframes example {
  0% {background-color: red;}
  100% {background-color: yellow;}
}

上述示例中,设置 animation-iteration-count 属性为 1,意味着动画只播放一次。

使用 infinite 无限循环播放动画

div {
  animation-name: example;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}

@keyframes example {
  0% {background-color: red;}
  50% {background-color: yellow;}
  100% {background-color: blue;}
}

上述示例中,将 animation-iteration-count 属性设置为 infinite,表示动画将无限循环播放。

从父元素继承 iteration-count 属性

.parent {
  animation-name: example;
  animation-duration: 2s;
  animation-iteration-count: 3;
}

.child {
  animation-name: child-example;
  animation-duration: 1s;
  animation-iteration-count: inherit; /* 从父元素继承 */
}

@keyframes example {
  0% {background-color: red;}
  50% {background-color: yellow;}
  100% {background-color: blue;}
}

@keyframes child-example {
  0% {opacity: 0;}
  100% {opacity: 1;}
}

上述示例中,通过设置 animation-iteration-count 属性为 inherit,使 .child 元素从其父元素 .parent 中继承该属性。

总结

CSS3 animation-iteration-count 属性用于控制动画循环的次数。值得注意的是,该属性定义在 keyframes 语句中会覆盖 animation 属性中设置的循环次数。此外,还可以通过设置 infinite 值来实现动画的无限循环播放,以及通过 initialinherit 值来重置或从父元素继承该属性。