CSS中的transition
和animation
是两种用于实现视觉效果变化的技术,它们在功能和使用场景上有一些重要的区别。了解这些差异可以帮助开发者更好地选择合适的工具来实现特定的动画效果。
transition
主要用于定义元素从一个状态平滑过渡到另一个状态的过程。它需要一个触发事件(如hover、click等)来启动,并且只能在两个状态之间进行简单的变换。
selector {
transition-property: all;
transition-duration: 2s;
transition-timing-function: ease-in-out;
transition-delay: 1s;
}
transition-property
: 指定应用过渡效果的CSS属性。transition-duration
: 定义过渡效果完成所需的时间。transition-timing-function
: 规定过渡效果的速度曲线。transition-delay
: 定义过渡效果开始之前的延迟时间。<div class="box"></div>
<style>
.box {
width: 100px;
height: 100px;
background-color: red;
transition: all 2s ease-in-out;
}
.box:hover {
transform: rotate(360deg);
background-color: blue;
}
</style>
animation
提供了更复杂的动画能力,允许定义多个关键帧来控制动画过程中的变化,而不仅仅是起始和结束状态。
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
selector {
animation-name: example;
animation-duration: 4s;
animation-timing-function: linear;
animation-delay: 2s;
animation-iteration-count: infinite;
animation-direction: alternate;
}
@keyframes
: 定义动画过程中不同阶段的样式。animation-name
: 引用@keyframes
规则。animation-duration
: 动画完成一个周期所需的时间。animation-timing-function
: 规定动画的速度曲线。animation-delay
: 定义动画开始前的延迟。animation-iteration-count
: 定义动画播放的次数。animation-direction
: 定义动画是否应该反向运行。<div class="animated-box"></div>
<style>
@keyframes colorChange {
0% {background-color: red;}
50% {background-color: green;}
100% {background-color: blue;}
}
.animated-box {
width: 100px;
height: 100px;
animation: colorChange 4s infinite;
}
</style>
特性 | Transition | Animation |
---|---|---|
状态变化 | 仅支持两态之间的简单转换 | 支持多态复杂变化 |
触发方式 | 需要用户交互或状态改变触发 | 可以自动触发 |
关键帧支持 | 不支持 | 支持 |
复杂度 | 较低 | 较高 |
在选择使用transition
还是animation
时,应考虑动画的复杂性和需求。如果只需要简单的状态切换,transition
可能是更好的选择;如果需要更复杂的动画效果,则应选择animation
。
flowchart TB A[开始] --> B{需要多态变化?} B --是--> C[选择Animation] B --否--> D{需要用户交互触发?} D --是--> E[选择Transition] D --否--> F[重新评估需求]