css实现动画效果
animation
上一个总结的transform+transition也能实现简单的动画,这一次可以通过@keyframes+animation实现更加复杂点的动画。
@keyframes
是动画的过程,可以理解为剧本,animation
是播放动画的机器,可以设置播放动画名称、播放时间、速率、次数、反向轮播。
animation:name duration timing-function delay iteration-count itrection
@keyframes anmationname{keyframes-process{css-styles;}}
值 | 描述 |
---|---|
animation-name | 规定需要绑定到选择器的 keyframe 名称。。 |
animation-duration | 规定完成动画所花费的时间,以秒或毫秒计。 |
animation-timing-function | 规定动画的速度曲线。 |
animation-delay | 规定在动画开始之前的延迟。 |
animation-iteration-count | 规定动画应该播放的次数。 |
animation-direction | 规定是否应该轮流反向播放动画。 |
keyframes-process有两种写法,如下:
@keyframes move{
from{width:10px;}
to{width:20px;}
}
@keyframes move{
0%{}
48%{}
!00%{}
}
/*这里的0%相当于from,100%相当于to,后一种方法更精细*/
注:来自w3cschool。
example
<style>
.ball{
width: 100px;
height: 100px;
border-radius:50%;
background-color: red;
/*transform-origin属性改变被转换元素的位置。下面的值是默认值*/
transform-origin: 50% 50% 0;
/*infinite无限次,alternate反向重播*/
animation:change 5s ease-out 2s infinite alternate;
}
@keyframes change{
50%{
transform: translate(100px,100px) rotate(50deg) scale(1.3);
background-color: blue;
}
100%{
transform: translate(0px,200px) rotate(50deg);
background-color: green;
}
}
</style>
<div class="ball"></div>
不过需要注意兼容问题,针对不同浏览器加上前缀(如-webkit-)。ie10以下浏览器不兼容。
3D景深
为了实现3D效果,需要给元素加上以下代码:
perspective:600;/*这个值可以理解为该元素离我们的视距*/
-webkit-perspective:600;
transform-style:preserve-3d;
通过以上代码, 我们可以做出很多炫酷的立体效果。
翻页:
<style>
.book{
perspective:700;
-webkit-perspective:700;
transform-style:preserve-3d;
background-color: gray;
width:500px;
height: 300px;
position:relative;
}
.page{
background-color:yellow;
border:1px solid black;
transform-origin:left;
width:240px;
height: 280px;
position:absolute;
top:10px;
right:10px;
line-height: 280px;
text-align:center;
font-size: 30px;
}
.left{
left:10px;
}
.p1{
animation:turn 3s linear infinite;
}
.p2{
animation:turn 3s linear 1.5s infinite;
}
@keyframes turn{
from{
transform:rotateY(0deg);
}
to{
transform:rotateY(-180deg);
}
}
</style>
<div class="book">
<div class="page"></div>
<div class="page p1"></div>
<div class="page p1">第一页</div>
<div class="page p2"></div>
<div class="page p2">第二页</div>
<div class="page left"></div>
</div>