CSS3 animation-fill-mode 属性


CSS3 animation-fill-mode属性

CSS3 animation-fill-mode属性指定动画执行前后元素样式的设置,也就是定义动画执行前后的起点和终点的状态。在CSS3中,共有以下四个取值:

  1. none
  2. forwards
  3. backwards
  4. both

none

默认值为none,这意味着动画将在执行完之后回到其原始状态,始终使用浏览器的初始状态(首次加载页面时的状态)来进行填充。

@keyframes example {
  from {background-color: red;}
  to {background-color: yellow;}
}
 
div {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: example;
  animation-duration: 3s;
  animation-fill-mode: none;
}

forwards

当animation-fill-mode被设置为“forwards”,动画完成后,元素将保持动画结束时的状态,不再返回到其初始状态。

@keyframes example {
  from {background-color: red;}
  to {background-color: yellow;}
}
 
div {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: example;
  animation-duration: 3s;
  animation-fill-mode: forwards;
}

backwards

当animation-fill-mode被设置为“backwards”,元素将在动画执行之前应用第一帧属性(例如:0%),在动画执行时返回到默认属性,如 100%, 并且动画结束后立即删除之前的属性。

@keyframes example {
  from {background-color: red;}
  to {background-color: yellow;}
}
 
div {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: example;
  animation-duration: 3s;
  animation-fill-mode: backwards;
}

both

最后一个值是“both”,即让元素在动画执行之前和之后应用属性。

@keyframes example {
  from {background-color: red;}
  to {background-color: yellow;}
}
 
div {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: example;
  animation-duration: 3s;
  animation-fill-mode: both;
}

总结

动画填充模式提供了多种动画展示方式。使用动画时,可以根据需要控制动画执行前后元素样式的变化。

注意:针对 animation-fill-mode:backwards 的动画,被调用到 `animation-play-state: paused` 状态的动画不会向后预填充任何属性; 相反,动画在那个点立即采用了他的变化输出。