CSS动画示例
- 什么是CSS动画
动画使元素逐渐从一种样式变为另一种样式,可以随意更改任意数量的CSS属性。如果需要使用CSS动画,必须首先为动画指定一些关键帧。关键帧包含元素在特定时间所拥有的的样式。
- @keyframes规则
如果在@keyframes规则中指定了CSS样式,动画将在特定时间逐渐从当前样式更改为新样式。要使动画生效,必须将动画绑定到某个元素。
- 将“example”动画绑定到
<div>
元素。动画将持续4秒钟,同时将div元素的背景颜色从“red”逐渐改为“yellow”。
/* 动画代码 */
@keyframes example {
from {
background-color: red;
}
to {
background-color: yellow;
}
}
/* 向此元素应用动画效果 */
div {
width: 100px;
height: 100px;
background-color: red;
animation-name: example;
/* 定义需要多长时间完成动画,默认是0s */
animation-duration: 4s;
}
- 页面刷新时,一个小方块转一圈回到原点。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>小方块动画</title>
<style>
div {
/* 引用动画:动画名称 动画时间 运动曲线 何时开始 播放次数 是否反方向 */
/* infinite不限次数 */
width: 100px;
height: 100px;
background-color: pink;
/* animation: go 2s ease 0s 2; */
animation: walk 2s;
}
/* 定义关键帧 */
@keyframes go {
from {
/* transform属性向元素应用2D或3D转换,允许我们对元素进行旋转、缩放、移动或倾斜 */
/* 沿着X轴移动元素 */
transform: translateX(0);
}
to {
transform: translateX(600px);
}
}
@keyframes walk {
0% {
transform: translate3d(0, 0, 0);
}
25% {
transform: translate3d(800px, 0, 0);
}
50% {
transform: translate3d(800px, 400px, 0);
}
75% {
transform: translate3d(0, 400px, 0);
}
100% {
transform: translate3d(0, 0, 0);
}
}
</style>
</head>
<body>
<div></div>
</body>
</html>
- 动画属性
属性 | 描述 |
---|---|
@keyframes | 规定动画模式。 |
animation | 设置所有动画属性的简写属性。 |
animation-delay | 规定动画开始的延迟。 |
animation-direction | 定动画是向前播放、向后播放还是交替播放。 |
animation-duration | 规定动画完成一个周期应花费的时间。 |
animation-fill-mode | 规定元素在不播放动画时的样式(在开始前、结束后,或两者同时)。 |
animation-iteration-count | 规定动画应播放的次数。 |
animation-name | 规定 @keyframes 动画的名称。 |
animation-play-state | 规定动画是运行还是暂停。 |
animation-timing-function | 规定动画的速度曲线。 |