一、关键帧定义
animation 节点称为关键帧 keyframes
keyframes 关键帧创建 由@keyframes开头,后面接动画的名称 加花括号
@keyframes animation-name {
/* 开始 */
from {
}
/* 结束 */
to {
}
}
animation-name 关键帧动画名称
from to 表示开始和结束的状态,也可以通过0%~100%数值指定多个状态
@keyframes animation-name { 0% { width:100px; } 30% { width:130px; } 60% { width:160px; } 100% { width:200px; } }
二、animation属性
animation (动画)属性:
animation:<animation-name> | <animation-duration> | <animation-timing-function> |
<animation-delay> | <animation-iteration-count> | <animation-direction> |
<animation-fill-mode> | <animation-play-state>
animation-name: 动画名称
animation-duration: 动画持续时间 单位s或者ms
animation-timing-function : 动画速度和时间函数 ,ease-in、ease-out
animation-delay: 动画在启动前延迟时间
animation-iteration-count:动画播放次数
animation-direction:是否应该轮流反向播放动画
animation-fill-mode:指定动画完成时,是否停留在最后一帧样式
animation-play-state:控制动画播放和暂停
注意:
浏览器对动画的支持情况比较好,仅有小部分移动浏览器需要使用-webkit-前缀,动画属性(-webkit-animation)和关键帧@规则(@-webkit-keyframes)都要用到
这就需要复制出有前缀和无前缀两套代码,可以考虑使用Autoprefixer来实现
2.1、 animation-name
配置多个名称使用逗号隔开
animation-name: animation1,animation2
2.2、 animation-iteration-count
设置动画在结束前的播放次数,1次或者无限次infinite
animation-iteration-count: <count> | infinite
指定多个值
animation-iteration-count:2, 0, infinite;
2.3、animation-direction 属性
animation-direction:normal | alternate | reverse | alternate-reverse
动画播放次数大于1时,默认情况下,每次播放完都从结束状态跳回到起始状态,再从头开始播放
该属性改变播放行为:
normal:表示按正常时间轴顺序循环播放
reverse:表示按正常时间轴反向播放,与normal相反
alternate:表示轮流进行,即动画在奇数次(1, 3, 5, …)正向播放,在偶数次(2, 4, 6, …)反向播放
alternate-reverse:与alternate相反
2.4、animation-fill-mode 属性
三、实例
<style> @keyframes over-and-back{ 0% { background-color: hsl(0,50%,50%); transform:translate(0); } 50% { transform: translate(50px); } 100% { background-color: hsl(270,50%,90%); transform: translate(0); } } .box{ width:100px; height:100px; background-color: green; /* 为元素应用动画 */ animation: over-and-back 1.5s linear 3; } </style> <div class="box">aaa</div>