CSS animation怎么使用?(山东数漫江湖)
animation可以为很多CSS属性添加动画,比如: color, background-color, height和width。animation的动画需要使用@keyframes来定义,随后被animation属性来调用。
element {
animation: pulse 5s infinite;
}
@keyframes pulse {
0% {
background-color: #001F3F;
}
100% {
background-color: #FF4136;
}
}
animation的子属性
animation-name: 声明@keyframes动画的名字animation-duration: 动画的时间周期animation-timing-function: 设置动画曲线,比如:ease或者linearanimation-delay: 元素加载后动画的开始时间animation-direction: 设置动画的方向animation-iteration-count: 动画需要被执行几次animation-fill-mode: 设置动画前/后需要被设置的值animation-play-state: 暂停/播放动画
这些子属性的用法如下:
@keyframes strech {
/* 这里声明动画 */
}
.element {
animation-name: strech;
animation-duration: 1.5s;
animation-timing-function: ease-out;
animation-delay: 0s;
animation-direction: alternate;
animation-iteration-count: infinite;
animation-fill-mode: none;
animation-play-state: running;
}
/* 也可以这么写 */
.element {
animation:
strech
1.5s
ease-out
0s
alternate
infinite
none
running;
}
下面是这些子属性的值:
| 属性 | 值 |
|---|---|
| animation-timing-function | ease, ease-out, ease-in, ease-in-out, linear, cubic-bezier(x1, y1, x2, y2) (e.g. cubic-bezier(0.5, 0.2, 0.3, 1.0)) |
| animation-duration | Xs 或 Xms |
| animation-delay | Xs 或 Xms |
| animation-iteration-count | X |
| animation-fill-mode | forwards, backwards, both, none |
| animation-direction | normal, alternate |
| animation-play-state | paused, running, running |
多个步骤
如果动画开始和结束的状态一样,那么可以这么写:
@keyframes pulse {
0%, 100% {
background-color: yellow;
}
50% {
background-color: red;
}
}
多个动画
可以用在选择器上用逗号分割来声明多个动画, 比如下面的代码,在切换颜色的时候同时移动:
.element {
animation:
pulse 3s ease infinite alternate,
nudge 5s linear infinite alternate;
}
@keyframes pulse {
0%, 100% {
background-color: red;
}
50% {
background-color: orange;
}
}
@keyframes nudge {
0%, 100% {
transform: translate(0, 0);
}
50% {
transform: translate(150px, 0);
}
80% {
transform: translate(-150px, 0);
}
}
性能
大多数的animation属性有性能问题,所以在给这些属性添加动画时要谨慎。但是以下几个属性是安全的:
- transform: translate()
- transform: scale()
- transform: rotate()
- opacity
什么属性可以添加动画?
MDN有个一个可以添加动画的列表。可以添加动画的属性一般为颜色和数字。
浏览器兼容性
| Chrome | Safari | Firefox | Opera | IE | Android | iOS |
|---|---|---|---|---|---|---|
| 6+ | 5+ | 5+ | 12+ | 10+ | 4.4+ |


浙公网安备 33010602011771号