CSS-动画进阶:从 @keyframes 到 Animation 属性全解析

144 阅读2分钟

前言

相比传统的 transition(过渡),animation(动画)提供了更强大的控制能力。它不需要触发条件,可以自动播放,并且通过“关键帧”能够实现极其复杂的视觉效果。

一、 动画的“两步走”战略

实现一个 CSS 动画通常分为两步:

  1. 定义动画:使用 @keyframes 规定不同时间点的样式状态。
  2. 调用动画:在目标元素上使用 animation 属性。

二、 Animation 属性详解(简写语法)

为了提高效率,我们通常使用简写方式:

animation: name duration timing-function delay iteration-count direction fill-mode;

1. 核心属性表

属性描述默认值
animation-name关键帧动画的名称
animation-duration动画周期时长(必须带单位,如 2s0
animation-timing-function速度曲线(平滑度控制)ease
animation-delay动画延迟启动时间0
animation-iteration-count播放次数(数字或 infinite1
animation-direction是否反向播放(如 alternatenormal
animation-fill-mode动画结束后的状态(如 forwards 停在终点)none

2. 关键属性深度解析

  • animation-timing-function (速度曲线)

    • ease:默认值,先慢后快再慢。
    • linear:匀速运动,适合背景滚动或旋转。
    • steps(n):逐帧动画,适合做像素画或 Loading 效果。
  • animation-iteration-count (循环次数)

    • n:播放 nn 次。
    • infinite:无限循环播放。

三、 实战案例:方块平移旋转

需求:方块在 3s 内匀速向右平移400px并旋转360°,无限循环。

.card {
  width: 100px;
  height: 100px;
  background: #ff4757;
  /* 针对 width 和 transform 设置过渡 */
  animation: moves 3s ease infinite;
}

@keyframes moves {
  0% {
    transform: translate(0,0) rotate(0deg);
  }
  100% {
    transform: translate(400px,0px) rotate(360deg);
  }
}

四、 进阶技巧与避坑指南

  1. 性能优化(优先使用 Transform)

    在动画中修改 margin-leftleft 会触发浏览器的重排 (Reflow) ,消耗大量性能。推荐使用 transform: translateX() ,它通过 GPU 加速,动画更加丝滑。

  2. 动画状态保持

    如果你想让动画播完后停留在最后一帧,请加上 forwardsanimation-fill-mode)。

  3. 单位不能省

    animation-duration 即使是 0 秒也必须带单位 0s,否则部分浏览器会判定为语法错误导致动画不生效。