animation是制作动画时使用的属性,之前的过渡都是需要人为触发,要么改变hover、要么就是改变css、要么就是改变类名,此时animation属性可以自己直接动画。
创建动画
关键字“ @keyframes”指示动画本身。
接下来动画的命名,“ XXX…”。
花括号{ }包含关键帧列表。在这种情况下,它是开始帧0%
和结束帧100%
。同样,开始和结束帧也可以写为关键字“ from ”和“ to”。
例如:
@keyframes bk{
from{
width: 100px;
}
to{
width: 300px;
}
}
注意,如果未指定起始帧(“ from ”,“ 0%”)或结束帧(“ to”,“ 100%”),浏览器将为他们设置动画功能的估算值,就像动画未应用。
光有动画是没有效果的,还需要把动画加到元素上去
div{
width: 100px;
height: 100px;
background-color: green;
animation-name: bk;
animation-duration: 1s;
}
animation-name:动画名称,“animation-duration”指出动画将播放多少秒。可以以秒((3s,65s,.4s))或毫秒((300ms,1000ms))表示。
效果如下:
除了animation-name和animation-duration属性外,还有其他的动画属性:
- animation-delay:功能可识别播放动画之前的延迟,以秒或毫秒为单位设置。
animation-name: bk;
animation-duration: 1s;
animation-delay: 3s;
- animation-iteration-count:动画播放次数。我们可以设置0、1、2、3…等中的任何正值,或者为无限重复设置“无限 ”。
animation-name: bk;
animation-duration: 1s;
animation-delay: 3s;
animation-iteration-count:2;
- animation-fill-mode:可标识元素在动画开始之前和完成之后处于哪种状态。
案例:
div{
width: 100px;
height: 100px;
background-color: pink;
animation-name: bk;
animation-duration: 3s;
}
@keyframes bk{
0%{
left: 0;
background-color: green;
}
50%{
left: 100px;
background-color: red;
}
100%{
left: 200px;
background-color: blue;
}
}
animation-fill-mode:forwards:动画完成后,元素状态将对应于最后一帧。
animation-fill-mode:forwards;
animation-fill-mode:backwards:动画完成后,元素状态将对应于第一帧。
animation-delay: 3s;
animation-fill-mode:backwards;
animation-fill-mode:both:动画开始之前,元素状态将与第一帧相对应,而在其完成之后将与最后一个帧相对应。
animation-delay: 3s;
animation-fill-mode:both;
animation-timing-function:动画时间函数,允许设置特殊功能,该功能负责动画重播速度。常用的函数名称有ease
, ease-in
, ease-out
, ease-in-out
, linear
, cubic-bezier()
。
使用效果和transition-timing-function差不多可参考:过渡transition