animation-fill-mode 属性规定当动画不播放时(动画不播放有两种情形:当动画完成后不播放时,或当动画有设置延迟时间未开始播放时),要应用到元素的样式。
默认情况下,CSS 动画在第一个关键帧播放完之前不会影响元素,在最后一个关键帧完成后停止影响元素。animation-fill-mode 属性可重写该行为。
属性可选值:
animation-fill-mode: none|forwards|backwards|both|initial|inherit
;
- none 默认值。动画在动画执行之前和之后不会应用动画中的任何样式到目标元素。
- forwards 在动画结束后(由 animation-iteration-count动画次数决定),元素将应用动画结束时属性值。
动画运行两次后停止,元素应用绿色背景和圆角边框。 - backwards 动画将应用在 animation-delay 定义期间启动动画的第一次迭代的关键帧中定义的属性值。
(1)未播放时应用 from关键帧中的值(当 animation-direction 为 “normal” 或 “alternate” 时)
(2) 未播放时应用 to 关键帧中的值(当animation-direction 为 “reverse” 或 “alternate-reverse” 时)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* body{position: relative;} */
div{
width: 100px;
height: 100px;
background: red;
position: relative;
margin: 10px 0px;
}
/* 不同的animation-direction */
.box1{animation:test 4s 3s backwards 2 normal;}
.box2{animation:test 4s 3s backwards 2 alternate;}
.box3{animation:test 4s 3s backwards 2 reverse;}
.box4{animation:test 4s 3s backwards 2 alternate-reverse;}
@keyframes test{
0%{left: 0px;background: yellow;}
100%{left: 300px; background: green;}
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
</body>
</html>
(下面的动图表示运行结果,开始为两个黄色盒子和两个绿色盒子)
在延迟时间内未播放时,前两个box应用了from中的样式;后两个box应用了to中的样式(left:300px;且背景色为绿色。)
- both 动画遵循 forwards 和 backwards 的规则。也就是说,动画会在两个方向上扩展动画属性。(设置延迟时,动画在未开始时运用动画中from或to的样式,在动画结束后也运用最后的样式。)
- initial 设置该属性为它的默认值。
- inherit 从父元素继承该属性。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* body{position: relative;} */
div{
width: 100px;
height: 100px;
background: red;
position: relative;
margin: 10px 0px;
}
/* animation-fill-mode*/
.box1{animation: test 4s 3s infinite;}
.box2{animation: test 4s 3s backwards infinite;}
.box3{animation: test 4s 2s forwards 2;}
.box4{animation: test 4s 2s both;} /*both:backwards和forwards同时生效 */
@keyframes test{
0%{left: 0px;background: yellow;}
100%{left: 300px; background: green;}
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
</body>
</html>
观察结果:(从四个盒子颜色分别为红黄红黄的时候开始观察)
(1)box1和box2都设置延迟,但box2在动画还没有执行时就由红色背景变成黄色背景,黄色背景是在0%中设置的,可以体会默认值与backwards的区别。
(2)box3(设置forwards)动画执行3次后结束应用了动画100%时的样式,停在左移300px的位置并且颜色变为绿色。
(3)box4 应用both,同时兼具forwards和backwards的特点,延迟未播放时应用了0%的属性,结束后应用了100%的属性。
简单地说,动画中的样式默认在动画开始前以及结束后都不应用到元素身上,但是我们可以通过设置backwards和forwards把动画的样式扩展到动画真正执行前以及动画执行结束后,还可以前后都进行扩展(both)。