css3 动画

css3 中的动画是使元素从一种样式逐渐变化为另一种样式的效果。

用百分比来规定变化发生的时间,或用关键词 "from" 和 "to",等同于 0%100%

0% 是动画的开始,100% 是动画的完成。

为了得到最佳的浏览器支持,应该始终定义 0% 和 100% 选择器。

例子: 

@keyframes myfirst
{
0%   {background: red;}
25%  {background: yellow;}
50%  {background: blue;}
100% {background: green;}
}

@-moz-keyframes myfirst /* Firefox */
{
0%   {background: red;}
25%  {background: yellow;}
50%  {background: blue;}
100% {background: green;}
}

@-webkit-keyframes myfirst /* Safari 和 Chrome */
{
0%   {background: red;}
25%  {background: yellow;}
50%  {background: blue;}
100% {background: green;}
}

@-o-keyframes myfirst /* Opera */
{
0%   {background: red;}
25%  {background: yellow;}
50%  {background: blue;}
100% {background: green;}
}

@keyframes 即 关键帧

在 @keyframes 中创建动画时,需要将其捆绑到某个选择器,否则不会产生动画效果。

通过规定至少以下两项 CSS3 动画属性,即可将动画绑定到选择器:

  • 规定动画的名称
  • 规定动画的时长

例子:

把 "myfirst" 动画捆绑到 div 元素,时长:5 秒:

div
{
  animation: myfirst 5s;
  -moz-animation: myfirst 5s;           /* Firefox */
  -webkit-animation: myfirst 5s;        /* Safari 和 Chrome */
  -o-animation: myfirst 5s;             /* Opera */
}
div
{
animation-name: myfirst;                 //动画名称
animation-duration: 5s;                  //动画完成一个周期所花费的时间
animation-timing-function: linear;    //动画的速度曲线  默认是"ease" 动画以低速开始,然后加快,在结束前变慢。 linear 动画从头到尾的速度是相同的。 ease-in 动画以低速开始。ease-out 动画以低速结束。
animation-delay: 2s;            //动画何时开始
animation-iteration-count: infinite;   //动画播放的次数  infinite 规定动画应该无限次播放。
animation-direction: alternate;      //动画是否在下一周期逆向播放 默认是”normal“ 动画应该正常播放。 alternate 动画应该轮流反向播放。
animation-play-state: running;       //动画是否正在运行或暂停  running 规定动画正在播放。 paused 规定动画已暂停。
animation-fill-mode: forwards; //forwards 当动画完成后,保持最后一个属性值(在最后一个关键帧中定义)。backwards 在 animation-delay 所指定的一段时间内,在动画显示之前,应用开始属性值(在第一个关键帧中定义)。 none 不改变默认行为。both 向前和向后填充模式都被应用。
}

与上面的动画相同,但是使用了简写的动画 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;
}