两者的区别
- transition 需要触发
- animation 不需要触发
transition 系列
常用属性
-
transition-property
- 需要过渡的属性
- 值为 all,所有属性都添加过渡效果
- 值为具体属性值,如 width,那么只有 width 属性添加过渡效果
-
transition-duration
- 实现过渡的时长
- 单位为毫秒
-
transition-timing-function
- 完成过渡的速度曲线函数
- 常用的值有 linear ease-in ease-out ease-in-out 等
- 可以使用贝塞尔曲线 https://cubic-bezier.com/#.17,.67,.83,.67
-
transition-delay
- 动画延迟
- 单位是毫秒
实例演示
<!-- transition 需要一个事件来触发变化
这里我使用点击事件,为需要过渡的元素动态添加类名 -->
<div @click="transitionActive = true">点击按钮改变</div>
<div class="transitionBox">
<div
:class="transitionActive ? 'active changeWidth' : 'changeWidth'"
>
宽变化
</div>
</div>
.changeWidth {
width: 100px;
height: 100px;
background: #ccc;
}
.changeWidth.active {
/* 添加 active 类名之后,宽度改线 */
width: 200px;
/* 想要让 width 属性实现过渡效果 */
transition-property: width;
/* 过渡时间为 1s */
transition-duration: 1s;
/* 设置速度曲线 */
transition-timing-function: ease-in-out;
}
<div @click="transitionActive = true">点击按钮改变</div>
<div class="transitionBox">
<div
:class="transitionActive ? 'active changeColor' : 'changeColor'"
>
色彩变化
</div>
</div>
.changeColor {
width: 100px;
height: 100px;
background: #ccc;
color: #333;
}
.changeColor.active {
/* 添加 active 类名之后,背景色和字体颜色改变 */
background: #000;
color: #fff;
/* 只改变背景色 */
/* transition: background, color 3s ease-in-out; */
/* 所有属性(背景色+字体颜色) 改变 */
transition: all 3s ease-in-out;
/* 变了一种速度曲线 */
/* transition: all 3s linear; */
}
animation 系列
常用属性
- animation-name
- 动画的名称,需要绑定到 keyframe 选择器上
- animation-duration
- 完成一个动画动作的时间
- 单位是毫秒
- animation-timing-function
- 完成动画的速度曲线函数
- 常用的值有 linear ease-in ease-out ease-in-out 等
- 可以使用贝塞尔曲线 https://cubic-bezier.com/#.17,.67,.83,.67
- animation-delay
- 动画延迟
- 单位是毫秒
- animation-iteration-count
- 动画播放的次数
- 值为 infinite 可以播放无数次
- 值为数字,可以播放指定次数
- animation-direction
- 是否轮流反向播放动画
- 值为 normal,正常播放
- 值为 alternate,动画轮流反向播放
实例演示
<!-- animation 不需要触发
可以立即执行 -->
<div class="animateBox">
<div class="changeWidth">宽变化</div>
</div>
.changeWidth {
width: 100px;
height: 100px;
background: #ccc;
/* 动画时长为 2s */
/* 设置速度曲线为 linear */
/* 设置动画一直不停播放 */
animation: widthCss 2s linear infinite;
/* 设置反向动画效果,相比于 widthCss,有回弹的效果 */
animation: widthCssType2 2s linear infinite alternate;
}
@keyframes widthCss {
0% {
width: 100px;
}
100% {
width: 200px;
}
/* 另外一种写法 */
/* from {
width: 100px;
}
to {
width: 200px;
} */
}
@keyframes widthCssType2 {
from {
width: 100px;
}
to {
width: 200px;
}
}
<!-- animation 不需要触发
可以立即执行 -->
<div class="animateBox">
<div class="changeColor">色彩变化</div>
</div>
.changeColor {
width: 100px;
height: 100px;
background: #ccc;
color: #333;
/* 动画时长为 2s */
/* 设置速度曲线为 ease-in-out */
/* 设置动画一直不停播放 */
animation: colorCss 2s ease-in-out infinite;
/* 动画只播放一次 */
/* animation: colorCss 2s ease-in-out; */
/* 动画播放5次 */
/* animation: colorCss 2s ease-in-out 5; */
}
@keyframes colorCss {
50% {
background: #000;
color: #fff;
}
}