CSS3 词条目录
前端Wiki/CSS3/进阶/动画 animation

animation 属性详解

animation 完整参数多达八项,按序是:

  • animation-name:剧本名。
  • animation-duration:单次时长。
  • animation-timing-function:帧间缓动,和 transition 一样支持 bezier。
  • animation-delay:延迟,负值表示「快进」直接从中间某刻开始。
  • animation-iteration-count:次数,数字或 infinite。
  • animation-direction:normal / reverse / alternate / alternate-reverse。
  • animation-fill-mode:重点。 forwards 保持最后一帧、backwards 应用第一帧(含延迟期间)、both 两者兼顾。没设它,动画结束会瞬间跳回原样式。
  • animation-play-state:running / paused,悬停暂停加载动画全靠它。

速记时前两个时间值按顺序解析:第一个是时长、第二个是延迟。多组动画用逗号叠加,可同时跑两段剧本。

本节要点八个参数中 fill-mode 最易漏:forwards 停在结尾、both 最保险;play-state:paused 可悬停暂停;速记里第一个时间是时长、第二个是延迟。
CSS
<style>
  .box {
    width: 60px; height: 60px;
    background: #7c4dff;
    border-radius: 8px;
    /* 时长2s 延迟.5s 播2次 停在最后 */
    animation: slide 2s ease .5s 2 forwards;
  }
  @keyframes slide {
    from { transform: translateX(0);   background: #7c4dff; }
    to   { transform: translateX(160px); background: #39c5cf; }
  }
</style>
<div class="box"></div>