CSS transition与animation的区别与选择

2025-05发布3次浏览

CSS中的transitionanimation是两种用于实现视觉效果变化的技术,它们在功能和使用场景上有一些重要的区别。了解这些差异可以帮助开发者更好地选择合适的工具来实现特定的动画效果。

CSS Transition

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>

CSS Animation

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>

区别与选择

特性TransitionAnimation
状态变化仅支持两态之间的简单转换支持多态复杂变化
触发方式需要用户交互或状态改变触发可以自动触发
关键帧支持不支持支持
复杂度较低较高

在选择使用transition还是animation时,应考虑动画的复杂性和需求。如果只需要简单的状态切换,transition可能是更好的选择;如果需要更复杂的动画效果,则应选择animation

flowchart TB
    A[开始] --> B{需要多态变化?}
    B --是--> C[选择Animation]
    B --否--> D{需要用户交互触发?}
    D --是--> E[选择Transition]
    D --否--> F[重新评估需求]