前言
最近在写项目的时候,发现很多地方的效果都可以用到Css动画和过渡来实现,冥冥之中感觉自己是会的,但是操作起来发现已经把这部分内容忘记的差不多了,所以就再来回顾一下。
过渡
简介
CSS3中,我们为了给某个元素添加某种效果是可以从一种样式转变到另一个的时候,我们就可以使用过渡来实现。比如:鼠标移入某个元素时想让其有一个平滑过渡的效果。那么他是如何工作的呢?其实就是元素从一种样式逐渐改变为另一种的效果。那么这里我们就需要规定两个东西,1【过渡完成的时间】2【要为谁添加css的样式属性】,如果不设置事件则默认为0,也就是没有过渡效果。
/*给box添加一个宽度渐变的过渡效果*/
.box{
width:10px;
height:20px;
background-Color:#cfa;
transition:width 2s;
}
/*当鼠标指针悬浮于box上时,宽度渐变为300px*/
.box:hover{
width:300px;
}
/*多个样式的过渡效果*/
.box{
width:10px;
height:20px;
background-Color:#cfa;
transition:width 2s,height 2s;
}
过渡属性
属性:transition-property
规定应用过渡Css属性的名称,有三个可选值all none property,分别代表的意思是:
all所有属性都获得过渡效果;none没有属性获得过渡效果;property定义应用过渡效果的属性名称列表,属性名称间用逗号隔开。 属性:transition-duration默认值为0,时间可以为毫秒或秒。
/*语法*/
transition-property: none|all| *property*;
属性:transition-timing-function切换效果的速度,默认ease)(下面列表作为了解)。
| 值 | 描述 |
|---|---|
| linear | 规定以相同速度开始至结束的过渡效果(等于 cubic-bezier(0,0,1,1))。 |
| ease | 规定慢速开始,然后变快,然后慢速结束的过渡效果(cubic-bezier(0.25,0.1,0.25,1))。 |
| ease-in | 规定以慢速开始的过渡效果(等于 cubic-bezier(0.42,0,1,1))。 |
| ease-out | 规定以慢速结束的过渡效果(等于 cubic-bezier(0,0,0.58,1))。 |
| ease-in-out | 规定以慢速开始和结束的过渡效果(等于 cubic-bezier(0.42,0,0.58,1))。 |
| cubic-bezier(n,n,n,n) | 在 cubic-bezier 函数中定义自己的值。可能的值是 0 至 1 之间的数值。 |
属性:transition-delay 延时,默认值0,可设置毫秒或秒。
属性:transition
/*语法格式*/
transition: property duration timing-function delay;
动画
简介
创建一个CSS动画,我们必须要了解keyframes则,改规则指定一个CSS样式和动画将逐步从目前的样式更改为新的样式。当我们使用keyframes建动画对的时候需要将其绑定到一个选择器上,否则动画不回有任何效果(动画名称和动画的时长这两个属性必须绑定到此选择器上)
注意: 我们在使用css动画的时候一定要考虑兼容性,这里不再一一赘述
动画的属性
- animation-duration完成一次所花费的时间(秒或者毫秒,默认0)
- animation-timing-function动画的速度曲线,默认值
ease - animation-delay动画何时开始,时延
- animation-fill-mode动画播放完成后是回到原位置还是停留到目标位置等
- animation-iteration-count规定动画播放的次数,默认1
- animation-direction规定动画播放完成后是否逆向播放
- animation-play-state规定动画是否正在运行或已暂停
- animation-iteration-count规定动画播放次数,默认1
animation-duration
animation-duration: time;/*time默认值为0,可以自行设置*
animation-delay
animation-delay: time;/*等待time后播放动画*/
animation-direction
animation-direction:属性值;/*可选的值有reverse反向播放;alternate奇数次正向,偶数次反向(alternate-reverse 反之);
animation-iteration-count
animation-iteration-count:次数或infinite;/*指定动画应该播放无限次(infinite)*/
animation-timing-function
ease低速开始,然后加快,结束前慢速linner动画从头到尾速度相同的ease-in-out动画以低速开始,低速结束
animation-fill-mode
both动画会在两个方向上扩展动画属性forwards播放完成后停留在那里
简写形式
animation: 动画名 持续时间 时延 播放次数 是否轮流反向播放 ;
案例
动画:小青蛙追船只
<div class="boat">
<img width="100%" src="./img/boat.png" alt="">
</div>
<div class="mike">
<img width="100%" src="./img/mike.png" alt="">
</div>
body {
margin: 0;
background: #F0FCFF url(./img/island.png) repeat-x 0 -650px;
/* 绑定对应的动画 */
animation: move-bg 8s forwards;
}
@keyframes move-bg {
0% {
background-position: 0 -650px;
}
100% {
background-position: -4000px -550px;
}
}
.boat {
width: 300px;
position: fixed;
top: 50%;
left: 50%;
margin-left: -150px;
}
.mike {
width: 200px;
position: fixed;
top: 60%;
animation: mike 4s 8s both;
}
@keyframes mike {
0% {
left: -200px;
}
100% {
left: 20%;
}
}
效果如下
总结
温故而知新,可以为师矣。🐱🏍