009-CSS 动画有哪些
前言
css 实现动画的方式有如下几种:
- transition 实现渐变动画
- transform 过渡动画
- animation 实现自定义动画
transition
- property:需要赋予过渡动画的属性,如 width、height 等。
- duration:过渡动画所需的时间。
timing-function
:过渡效果。- delay:过渡效果开始作用之前需要等待的时间。
timing-function
的值如下表格:
值 | 描述 |
---|---|
linear | 匀速进行(等同 cubic-bezier(0, 0, 1, 1) ) |
ease | 由慢到快再到慢(等同 cubic-bezier(.25, .1, .25, 1) ) |
ease-in | 由慢到快(等同 cubic-bezier(.42, 0, 1, 1) ) |
ease-in-out | 由快到慢(等同 cubic-bezier(.42, 0, .58, 1) ) |
ease-out | 越来越慢(等同 cubic-bezier(0, 0, .58, 1) ) |
cubic-bezier | 在 cubic-bezier 函数中定义自己的值,可能的值是 0 至 1 之间的数值 |
鼠标移动上去发生过渡动画效果,举个例子:
<div class="box"></div>
.box {
width: 50px;
height: 10px;
cursor: pointer;
background-color: #0ff;
transition: width .2s ease;
&:hover {
width: 200px;
}
}
transform
常用的功能如下:
- translate:平移
- rotate:旋转
- scale:缩放
- skew:倾斜
它常和 transition 配合使用,下面举个例子:
<div class="box"></div>
.box {
width: 50px;
height: 50px;
cursor: pointer;
background-color: #0ff;
transition: all .2s ease;
&:hover {
transform: scale(.8, 1.5) translate(150px, 10px) rotate(90deg) skew(10deg);
}
}
运行上面代码的结果是盒子放大、平移、旋转、倾斜。
animation
它的属性如下表格:
属性名 | 描述 | 属性值 |
---|---|---|
animation-name | 指定 @keyframes 动画的名称 | |
animation-duration | 指定一个动画周期的时长,默认值为 0s,表示无动画 | |
animation-timing-function | 指定动画计时函数,即动画的速度曲线,默认是 ease | linear、ease、ease-in、ease-out、ease-in-out |
animation-delay | 定义动画于何时开始,默认是 0 | |
animation-iteration-count | 定义动画在结束前运行的次数 可以是 1 次 无限循环 | infinite(无限次) |
animation-direction | 指示动画是否反向播放 | normal、reverse、alternate、alternate-reverse |
animation-fill-mode | 设置 CSS 动画在执行之前和之后如何将样式应用于其目标 | forwards、backwards、both |
animation-play-state | 指定动画播放状态,正在运行或暂停。默认是 running | running、pauser |
通过 @keyframes
来定义关键帧,例如让一个元素旋转一周,如下:
<div class="box">6</div>
.box {
display: flex;
align-items: center;
justify-content: center;
width: 50px;
height: 50px;
background-color: red;
border-radius: 50%;
animation: my-animation 2s;
}
// 方法一
@keyframes my-animation {
0% {
transform: rotate(0deg);
}
50% {
transform: rotate(180deg);
}
100% {
transform: rotate(360deg);
}
}
// 方法二
// @keyframes my-animation {
// from {
// transform: rotate(0deg);
// }
// to {
// transform: rotate(360deg);
// }
// }
上面两种方法均可达到旋转一周的效果,其中 from
表示最开始的那一帧,to
表示结束时的那一帧。
部分答案整理自网络资源