css3动画讲解,关于css3的@keyframes和animation

通过css3我们可以创建动画,它能取代gif图片、Flash、Js动画等,css3的animation动画是应用在html的DOM元素上的,通过样式来实现的。

@keyframes 规则

@Keyframes我们可以把他理解为“关键帧”,它的规则是:创建由当前样式逐渐改为新样式的动画效果。对于一个"@keyframes"中的样式规则是由多个百分比构成的如“0%”到"100%"之间,我们可以使用“from”和“to”来代表一个动画是从哪开始,到那结束,"from“就相当与0%,”to"就相当于100%。

实例:

@keyframes myfirst{ /*动画名称:myfirst */
  from {background: red;}/*0%*/
  to {background: yellow;}/*100*/
}
//或者写成百分百的形式:
@keyframes myfirst{ /*动画名称:myfirst */
  0%   {background:red;}
  25%  {background:yellow;}
  50%  {background:blue;}
  100% {background:green;}
}

为了兼容浏览器,所以一般要加前缀:@-moz-keyframes兼容/* Firefox */、@-webkit-keyframes兼容/* Safari 和 Chrome */、@-o-keyframes兼容/* Opera */。

@keyframes应该保证定义了 0% 和 100%,这样才能保证浏览器最佳的显示效果。

animation

@Keyframes定义好了后,我们需要通过animation去调用刚才定义好的动画,CSS3的animation类似于transition属性,他们都是随着时间改变元素的属性值。他们主要区别是transition需要触发一个事件(hover事件或click事件等)才会随时间改变其css属性;而animation在不需要触发任何事件的情况下也可以显式的随着时间变化来改变元素css的属性值,从而达到一种动画的效果。anmiation是所有动画属性的简写属性:

属性描述
animation所有动画属性的简写属性,除了 animation-play-state 属性。
animation-name规定 @keyframes 动画的名称。
animation-duration规定动画完成一个周期所花费的秒或毫秒。默认是 0。
animation-timing-function规定动画的速度曲线。默认是 "ease"。
animation-delay规定动画何时开始。默认是 0。
animation-iteration-count规定动画被播放的次数。默认是 1。
animation-direction规定动画是否在下一周期逆向地播放。默认是 "normal"。
animation-play-state规定动画是否正在运行或暂停。默认是 "running"。
animation-fill-mode规定对象动画时间之外的状态。

同样为了兼容,都需要添加对应的前缀。

实例:

div
{
animation-name: myfirst;
animation-duration: 5s;
animation-timing-function: linear;
animation-delay: 2s;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-play-state: running;
/* Firefox: */
-moz-animation-name: myfirst;
-moz-animation-duration: 5s;
-moz-animation-timing-function: linear;
-moz-animation-delay: 2s;
-moz-animation-iteration-count: infinite;
-moz-animation-direction: alternate;
-moz-animation-play-state: running;
/* Safari 和 Chrome: */
-webkit-animation-name: myfirst;
-webkit-animation-duration: 5s;
-webkit-animation-timing-function: linear;
-webkit-animation-delay: 2s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-direction: alternate;
-webkit-animation-play-state: running;
/* Opera: */
-o-animation-name: myfirst;
-o-animation-duration: 5s;
-o-animation-timing-function: linear;
-o-animation-delay: 2s;
-o-animation-iteration-count: infinite;
-o-animation-direction: alternate;
-o-animation-play-state: running;
}

办公资源网址导航https://www.wode007.com

与上面的动画相同,但是使用了简写的动画 animation 属性:

div
{
animation: myfirst 5s linear 2s infinite alternate;
/* Firefox: */
-moz-animation: myfirst 5s linear 2s infinite alternate;
/* Safari 和 Chrome: */
-webkit-animation: myfirst 5s linear 2s infinite alternate;
/* Opera: */
-o-animation: myfirst 5s linear 2s infinite alternate;
}