一、介绍
animation是CSS3中的一个简写属性,可以通过设置六个动画属性来实现动画效果。这六个属性分别为动画名称、动画时间、速度曲线、动画延迟、播放次数及动画是否反向播放。
语法格式:
animation: name duration timing-function delay iteration-count direction fill-mode play-state;
属性值 | 说明 | 取值 |
---|---|---|
animation-name | 指定要绑定到选择器的关键帧的名称 | 字符串 |
animation-duration | 动画指定需要多少秒或毫秒完成 | 如:5s |
animation-timing-function | 设置动画将如何完成一个周期 | 如:linear 匀速 |
animation-delay | 设置动画在启动前的延迟间隔。 | 如:3s |
animation-iteration-count | 定义动画的播放次数。 | 1(动画播放次数为1次) |
animation-direction | 指定是否应该轮流反向播放动画。 | 如:alternate(设置动画为反向播放 ) |
animation-fill-mode | 规定当动画不播放时(当动画完成时,或当动画有一个延迟未开始播放时),要应用到元素的样式。 | 如:none-不做任何改变 |
animation-play-state | 指定动画是否正在运行或已暂停。 | 如:running-执行动画 |
二、关键帧的书写
第一种写法:
div
{
width:100px;
height:100px;
background:red;
position:relative;
animation:myfirst 5s infinite;
animation-direction:alternate;
}
@keyframes right
{
0% {background:red; left:0px; top:0px;}
25% {background:yellow; left:200px; top:0px;}
50% {background:blue; left:200px; top:200px;}
75% {background:green; left:0px; top:200px;}
100% {background:red; left:0px; top:0px;}
}
其中right就是关键帧的名字。
animation:myfirst 5s 1;myfirst就是关键帧的名字,5s表示整个动画完成的时间,infinite(无数次)代表动画执行的次数。
-
0% {background:red; left:0px; top:0px;}的意思就是从(0,0)坐标开始,此时元素在左上角不动。
-
25% {background:yellow; left:200px; top:0px;}的意思就是从向左移动200px,高度为0,此时元素在右上角。
-
50% {background:blue; left:200px; top:200px;}的意思就是从保持左边200px不变,将高度增加200px,这样就向下移动了200px,此时元素在右下角。
-
75% {background:green; left:0px; top:200px;}的意思就是从保持高度不变,将左边距归0,这样元素就使从200px移动到0px,相当于就是向右移动了,此时元素在左下角。
-
100% {background:red; left:0px; top:0px;}的意思就是将左边距和上边距都归0,就相当于回到了最开始的位置,此时元素在左上角。
第二种写法:
当只有0%和100%时可以用from to表示,from代表开始,to代表结束。
div
{
width:100px;
height:100px;
background:red;
position:relative;
animation:mymove 5s infinite;
animation-direction:alternate;
}
@keyframes mymove
{
from {left:0px;}
to {left:200px;}
/*
上面的from to等价于下面的0% 100%,两者选其一
*/
0% {left:0px;}
100% {left:200px;}
}