动画和过渡类似,都是可以实现一些动态效果,不同的是过渡需要在某个属性发生变化时才能触发,动画可以自动触发动画
一、设置关键帧
设置动画效果,必须先要设置一个关键帧,关键帧设置了动画每一个步骤
语法:@keyframes 动画名 {}
代码演示:
@keyframes text {
/* from表示动画开始位置 也可以使用0%*/
from {margin-left: 0;}
/* to动画的结束位置 也可以使用100%*/
to {margin-left: 500px;}
}
二、设置动画属性,属性如下
1:animation-name 设置动画的名字,和@keyframs相对应
2:animation-duration 动画执行时间 duration [djuə'reiʃən]
3:animation-delay 动画执行延时
4:animation-timing-function 动画执行的方式
5:animation-iteration-count [,itə'reiʃən] 动画执行的次数
可选值:次数(数字)
infinite ['infinət] 无限循环
6:animation-direction 指定动画运行的方向
可选值
normal 默认值: 从from向to运行,每次都是这样
reverse 从to到from运行,每次都是这样
alternate 从from向to运行,重复执行动画时反向执行
alternate-reverse 从to向from运行,重复执行动画时反向执行
7:animation-play-state 设置动画的执行状态
可选值:
running 默认值 动画执行
paused 动画暂停
8:animation-fill-mode 动画的填充模式
可选值:
none默认值 动画执行完毕 元素回到原来的位置
forwards 动画执行完毕,会停止在动画结束的位置
ackwards 动画延时等待时,元素就会处于开始位置
both 结合了forwards和ackwards的特点
9:animation: ; 动画简写方式
<!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>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.box1 {
width: 600px;
height: 600px;
background-color: silver;
}
.box1 div {
width: 100px;
height: 100px;
margin-bottom: 50px;
margin-left: 0;
}
/* 第一步:设置关键帧 */
@keyframes text {
/* from表示动画开始位置 也可以使用0%*/
from {
margin-left: 0;
}
/* to动画的结束位置 也可以使用100%*/
to {
margin-left: 500px;
}
}
/*第二步 设置box2的动画 animation [ˌænɪˈmeɪʃ(ə)n] */
.box2 {
background-color: #bfa;
animation-name: text;
animation-duration: 1s;
animation-delay: 1s;
animation-timing-function: ease-in-out;
animation-iteration-count: 2;
animation-direction: alternate-reverse;
animation-play-state: running;
animation-fill-mode: forwards;
/* 简写模式 */
/* animation: text 2s 2 2s alternate-reverse; */
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
</html>