css3中通过@keyframes定义动画,animation设置动画属性,从而实现动画效果;
在animation属性当中,可以规定动画的名称、整个动画的运行时间、运动的速度曲线以及其延迟时间、播放次数等。
animation
animation作为一个复合属性,包括了以下动画属性。
-
animation-name -------------------------------------规定动画名称
-
animation-duration ---------------------------------规定动画完成一次的时间
-
animation-timing-function ----------------------规定动画的运动速度曲线
-
animation-delay ------------------------------------规定动画的延迟时间
-
animation-iteration-count -----------------------规定动画的播放次数
-
animation-direction ------------------------------规定动画下一周期是否逆向开始
-
animation-fill-mode -------------------------------规定动画时间之外的状态
-
animation-play-state ------------------------------规定动画的运行和暂停
animation-timing-function
规定动画的速度曲线。默认是 "ease"。常用的运动速度曲线还有以下几种:
- linear:线性过渡。
- ease-in:由慢到快。
- ease-out:由快到慢。
- ease-in-out:由慢到快再到慢。
也可以直接使用贝塞尔曲线规定运行的速度曲线,贝塞尔曲线的4个数值需在[0, 1]区间内。
animation-direction
规定动画是否在下一周期逆向播放。默认是 "normal"。
- reverse:反方向运动
- alternate:先正常方向再反方向运动,持续交替
- alternate-reverse:先反方向再正常方向运动,持续交替
animation-fill-mode
规定对象动画时间之外的状态。常用值如下:
- none:默认值
- forwards:设置对象状态为动画结束时的状态
- backwards:设置对象状态为动画开始时的状态
圆形运动轨迹
实现代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>沿圆形轨迹运动</title> <style type="text/css"> *{ margin: 0; padding: 0; } html,body{ height: 100%; } #trajectory { width: 300px; height: 300px; border: 4px solid #949494; border-radius: 50%; position: relative; left: calc(50% - 153px); top:calc(50% - 153px); } @keyframes moveX{ 0% {left: -22px;} 100% {left: 282px;} } @keyframes moveY{ 0% {top: -22px;} 100% {top: 282px;} } #move { width: 40px; height: 40px; font-size: 12px; background-color: #32c33a; border-radius: 50%; position: absolute; left:-22px; top:-22px; animation: moveX 4s cubic-bezier(0.36,0,0.64,1) -2s infinite alternate, moveY 4s cubic-bezier(0.36,0,0.64,1) 0s infinite alternate; } </style> </head> <body> <div id="trajectory"> <div id="move">Immortal brother</div> </div> </body> </html>
以上代码的注意点如下:
- 对body高度100%的设置原因在于html5环境下body的默认高度为0
- calc在使用过程中,值与值之间的“-”和“+”两端的空格必不可少
- 动画当中的left和top值为物体运动的起始位置和结束位置,要注意border值
- 动画一次执行的运动轨迹仅为一半
- 速度曲线:cubic-bezier(0.36,0,0.64,1);
- 两个方向的延迟时间的设置 X:-2s;Y : 0s
- 先正方向再反方向持续交替运行 :alternate