CSS 代码:
@keyframes kf1 { 0% { width:150px; background:#000; } 50% { width:50px; background:#00f; } 100% { width:150px; background:#ff0; } } div { width:150px; height:100px; background:#ff0; animation:kf1 5s; }
先用 @keyframes 指定一个动画,再用 animation 指定动画和所需时间。
@keyframes 中 0%、50%、100% 表示动画各个时间阶段的样式,也可用其他百分比,另外 0% 可用 from 代替,100% 可用 to 代替。
说明:50% 不是必写。
说明:终点状态(100%、to)那里,也可以不写,不写的话,它就自动响应最终的样式。
再提供一个旋转的代码吧:
@keyframes rotateOn { from { transform:rotate(0); } to { transform:rotate(90deg); } }
animation 全部参数
第一个参数表示动画名称,即 @keyframes 后面的名称。
第二个参数表示动画所需的 s 或 ms。
第三个参数是动画时间曲线(比如先快后慢?)与 transition 中的一致。
第四个参数是首次播放时延时的 s 或 ms。
第五个参数是播放次数,infinite 表示一直循环播放。
第六个参数是播放方式,比如反向播放。
第七个参数是指动画播放前后,是否应用相关样式到目标元素。
第八个参数是指动画是否正在运行或已暂停。
第七个参数举例解释
第七个参数值有:none(默认值)、forwards、backwards、both。
<style type="text/css"> @keyframes ani { from { width:50px; height:50px; } to { width:100px; height:100px; } } .c1 { width:50px; height:50px; background:red; } .c1.animation { animation:ani 1s ease-out forwards; } /*注意这里*/ </style> <div class="c1 animation"></div>
如上,指定了 forwards,此时根据 to 中指定的样式 width:100px; height:100px; 设置 div 的最终样式。如果不指定,它又会跳回 50px 去。
上述代码,其实等效于:
<style type="text/css"> @keyframes ani { from { width:50px; height:50px; } to { width:100px; height:100px; } } .c1 { width:50px; height:50px; background:red; } .c1.animation { width:100px; height:100px; animation:ani 1s ease-out; } /*注意这里*/ </style> <div class="c1 animation"></div>