CSS动画

CSS动画允许你创建流畅的过渡效果和复杂的动画序列,无需JavaScript的帮助。动画由@keyframes规则定义,并通过animation属性应用于元素。

动画基础

@keyframes规则

@keyframes规则用于定义动画的关键帧,即动画在不同时间点的状态。

css
@keyframes example {
  0% {background-color: red;}
  50% {background-color: yellow;}
  100% {background-color: blue;}
}

animation属性

animation属性是一个简写属性,用于设置动画的各种参数:

css
.element {
  animation: example 5s infinite;
}

动画属性

animation-name

指定要应用的@keyframes名称。

css
.element {
  animation-name: example;
}

animation-duration

指定动画完成一个周期所需的时间(秒或毫秒)。

css
.element {
  animation-duration: 5s;
}

animation-timing-function

指定动画的速度曲线。

css
.element {
  animation-timing-function: ease;
}

常用的值:

  • ease:默认值,慢入→快→慢出
  • linear:匀速
  • ease-in:慢入
  • ease-out:慢出
  • ease-in-out:慢入慢出
  • cubic-bezier(n,n,n,n):自定义贝塞尔曲线

animation-delay

指定动画开始前的延迟时间。

css
.element {
  animation-delay: 2s;
}

animation-iteration-count

指定动画应该播放的次数。

css
.element {
  animation-iteration-count: infinite;
}

animation-direction

指定动画是否应该反向播放。

css
.element {
  animation-direction: alternate;
}

常用的值:

  • normal:默认值,正向播放
  • reverse:反向播放
  • alternate:正向→反向→正向…
  • alternate-reverse:反向→正向→反向…

animation-fill-mode

指定动画播放前后元素的样式。

css
.element {
  animation-fill-mode: forwards;
}

常用的值:

  • none:默认值,动画结束后回到初始状态
  • forwards:保持动画结束时的状态
  • backwards:在延迟期间应用第一个关键帧的状态
  • both:同时应用forwards和backwards

animation-play-state

指定动画是否正在运行或暂停。

css
.element:hover {
  animation-play-state: paused;
}

动画示例

简单动画

css
@keyframes fadeIn {
  from {opacity: 0;}
  to {opacity: 1;}
}

.fade-in-element {
  animation: fadeIn 2s ease-in;
}

复杂动画

css
@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {transform: translateY(0);}
  40% {transform: translateY(-30px);}
  60% {transform: translateY(-15px);}
}

.bouncing-element {
  animation: bounce 2s infinite;
}

动画性能

  • 优先使用transformopacity属性进行动画,因为它们可以通过GPU加速
  • 避免对布局属性(如width、height、margin等)进行动画,因为它们会触发重排
  • 使用will-change属性提示浏览器哪些属性将被动画化
css
.animated-element {
  will-change: transform, opacity;
}

浏览器兼容性

CSS动画在所有现代浏览器中都有很好的支持,但需要考虑旧版本浏览器的兼容性:

  • Chrome 4+ (带-webkit-前缀)
  • Firefox 5+ (带-moz-前缀)
  • Safari 4+ (带-webkit-前缀)
  • IE 10+
  • Edge 12+

对于旧版本浏览器的支持,可以添加浏览器前缀:

css
@keyframes example {
  /* 标准语法 */
}

@-webkit-keyframes example {
  /* Safari和Chrome */
}

.element {
  animation: example 5s;
  -webkit-animation: example 5s; /* Safari和Chrome */
}