一、是什么
CSS动画(CSS Animations)是为层叠样式表建议的允许可扩展标记语言(XML)元素使用CSS的动画的模块
即指元素从一种样式逐渐过渡为另一种样式的过程
常见的动画效果有很多,如平移、旋转、缩放等等,复杂动画则是多个简单动画的组合
css实现动画的方式,有如下几种:
- transition 实现渐变动画
- transform 转变动画
- animation 实现自定义动画
二、实现方式
transition 实现渐变动画
transition的属性如下:
- property:填写需要变化的css属性
- duration:完成过渡效果需要的时间单位(s或者ms)
- timing-function:完成效果的速度曲线
- delay: 动画效果的延迟触发时间
其中timing-function的值有如下:
注意:并不是所有的属性都能使用过渡的,如display:none<->display:block
举个例子,实现鼠标移动上去发生变化动画效果
<style>
.base{
width:100px;
height:100px;
display:inline-block;
background-color:#0EA9FF;
border-width:5px;
border-style:solid;
border-color:#5daf34;
transition-property:width,height,background-color,border-width;
transition-duration:2s;
transition-timing-function:ease-in;
transition-delay:500ms;
}
/*简写*/
/*transition:all2sease-in500ms;*/
.base:hover{
width:200px;
height:200px;
background-color:#5daf34;
border-width:10px;
border-color:#3a8ee6;
}
</style>
<div></div>
transform 转变动画
包含四个常用的功能:
- translate:位移
- scale:缩放
- rotate:旋转
- skew:倾斜
一般配合transition过度使用
注意的是,transform不支持inline元素,使用前把它变成block
举个例子
<style>
.base{
width:100px;
height:100px;
display:inline-block;
background-color:#0EA9FF;
border-width:5px;
border-style:solid;
border-color:#5daf34;
transition-property:width,height,background-color,border-width;
transition-duration:2s;
transition-timing-function:ease-in;
transition-delay:500ms;
}
.base2{
transform:none;
transition-property:transform;
transition-delay:5ms;
}
.base2:hover{
transform:scale(0.8,1.5)rotate(35deg)skew(5deg)translate(15px,25px);
}
</style>
<div></div>
可以看到盒子发生了旋转,倾斜,平移,放大
animation 实现自定义动画
animation是由 8 个属性的简写,分别如下:
CSS动画只需要定义一些关键的帧,而其余的帧,浏览器会根据计时函数插值计算出来,
通过@keyframes来定义关键帧
因此,如果我们想要让元素旋转一圈,只需要定义开始和结束两帧即可:
@keyframesrotate{
from{
transform:rotate(0deg);
}
to{
transform:rotate(360deg);
}
}
from表示最开始的那一帧,to表示结束时的那一帧
也可以使用百分比刻画生命周期
@keyframesrotate{
0%{
transform:rotate(0deg);
}
50%{
transform:rotate(180deg);
}
100%{
transform:rotate(360deg);
}
}
定义好了关键帧后,下来就可以直接用它了:
animation:rotate2s;
三、总结
以上就是CSS3常见动画的实现方式的详细内容,更多关于CSS3 动画的实现的资料请关注悠久资源网其它相关文章!