一、动画效果
动画效果与过渡效果的区别在于,过渡效果一般用于用户与浏览器有交互的情况下,网页出现一些动态的变化。动画效果可以实现网页没有任何交互的情况下,自己就会展示动态效果。
1.定义动画
通过@keyframes可以定义动画效果。
代码如下(示例):
.box {
width: 200px;
height: 200px;
background-color: #00f;
animation: anim 5s linear 0.5s;
}
@keyframes anim{
0%{
transform: translate(0px,0px)
}
100%{
transform: translate(900px,100px)
}
}
在上面的代码中,我们可以了解到css3动画的基本语法:
首先,我们需要用@keyframes定义一个动画,在上面的代码中,我们定义的动画名字为anim。
然后在花括号中定义动画的具体细节,0%位起始状态,100%为结束状态,我们也可以用其他的百分比定义动画在不同阶段的不同状态。
最后,需要在元素选择器中调用这个动画,animation属性可以调用动画,第一个值是动画名称,后面的三个值分别是动画的时间,动画函数和延时时间,这个与我们之前学的过渡效果设置方法很类似。
2.设置动画
在上面的代码中,元素运行到100%的位置就会直接回到0%的位置,这样看起来效果很不平滑,为了让效果更连贯,我们可以让0%和100%的样式是相同的。
代码如下(示例):
.box {
width: 200px;
height: 200px;
background-color: #00f;
animation: anim 10s;
}
@keyframes anim {
0% {
transform: translate(0px, 0px)
}
25%{
transform: translate(500px, 0px)
}
50%{
transform: translate(500px, 500px)
}
75%{
transform: translate(0px, 500px)
}
100%{
transform: translate(0px, 0px)
}
}
3.让动画更连贯
在上面的代码中,元素经过了四次运动,最终回到了起始位置,我们还可以继续修改案例,让元素的动画效果更佳丰富。
代码如下(示例):
.box {
width: 200px;
height: 200px;
background-color: #00f;
animation: anim 10s linear;
}
@keyframes anim {
0% {
transform: translate(0px, 0px) rotate(0);
}
25% {
transform: translate(500px, 0px) rotate(360deg);
}
50% {
transform: translate(500px, 500px) rotate(720deg);
}
75% {
transform: translate(0px, 500px) rotate(1080deg);
}
100% {
transform: translate(0px, 0px) rotate(1440deg);
}
}
4.循环动画
我们还可以通过设置animation-iteration-count属性设置动画播放的次数,如果值为infinite,则动画不断地循环播放。
代码如下(示例):
.box {
width: 200px;
height: 200px;
background-color: #00f;
animation: anim 10s linear;
animation-iteration-count:infinite;
}
5.停止动画
我们还可以通过设置animation-play-state属性让动画停止。
代码如下(示例):
.box {
width: 200px;
height: 200px;
background-color: #00f;
animation: anim 10s linear;
animation-iteration-count: infinite;
}
.box:hover{
animation-play-state: paused;
}
这样当我们鼠标悬浮在元素之上的时候,动画就会停下来,当我们鼠标离开元素,动画又会开始运行。