动画(animation):和过渡类似,都是可以实现一些动态的效果,不同的是过渡需要在某个属性发生变化时才可以触发,而动画效果则可以自动触发动态效果。设置动画效果必须先要设置一个关键帧,关键帧设置了动画执行的每一个步骤。关键帧设置的格式如下:
<style>
/* 定义动画关键帧,关键帧的名字为test */
@keyframes test{
/* from表示动画的开始位置,也可以使用0%来表示。 */
from{
margin-left: 0;
}
/* to表示动画的结束位置,也可以使用100%来表示。 */
to{
margin-left: 100%;
}
}
</style>
定义好关键帧后,就可以在响应的元素中使用这个关键帧了,关键帧的属性和 过渡 中的一些属性设置方式是一样的,关键帧的一些常见属性如下:
animation-name: 要对当前元素生效的关键帧的名字,如:animation-name: test;
animation-duration: 动画的执行时间,如:animation-duration: 4s;
animation-iteration-count: 动画执行的次数,如:animation-iteration-count: 4,可选值:数字或infinite,其中数字的大小就是执行的次数,而infinite则表示无限次。
animation-timing-function: 指定动画执行的时序函数;
animation-direction: 指定动画运行的方向,可选值如下:
animation-play-state: 控制动画的运行状态,可选值如下:
animation-fill-mode: 动画的填充模式,可选值如下:
可以使用animation一个属性来实现上面所介绍的所有属性,在使用animation时,格式如下:
animation: name duration timing-function delay iteration-count direction fill-mode;
需要注意的是,在写时间时,持续时间是在延迟时间的前面即可。
/*表示动画关键帧的名字为test,延迟一秒钟之后开始执行,持续时间两次,重复执行4次,时序函数为匀速运动,重复执行时方向为alternate。*/
animation: test 2s linear 1s 4 alternate;
练习代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>动画</title>
<style>
.box1{
width: 700px;
height: 500px;
background-color: silver;
}
.box2{
width: 100px;
height: 100px;
background-color: #bfa;
margin-left: 10px;
/* animation-name: test; */
/* animation-duration: 4s; */
/* animation-timing-function: linear; */
/* animation-iteration-count: 4; */
/* animation-direction: alternate; */
/* animation-fill-mode: backwards; */
/* animation-delay: 2s; */
animation: test 2s linear 1s 4 alternate;
}
/* 定义动画关键帧,关键帧的名字为test */
@keyframes test{
/* from表示动画的开始位置,也可以使用0%来表示。 */
from{
margin-left: 50px;
background-color: orange;
}
/* to表示动画的结束位置,也可以使用100%来表示。 */
to{
margin-left: 600px;
background-color: yellow;
}
}
/* 控制动画的运行 */
/* .box1:hover .box2{
animation-play-state: paused;
} */
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
</html>