CSS动画技术中animation的使用介绍

CSS中的 animation 属性可以让很多其它CSS属性产生动画效果,比如color, background-color, heightwidth等。当然,你需要为每个动画定义@keyframes CSS规则,animation需要调用这些@keyframes产生动画效果,比如:

.element {
  animation: pulse 5s infinite;
}

@keyframes pulse {
  0% {
    background-color: #001F3F;
  }
  100% {
    background-color: #FF4136;
  }
}

在每个 @keyframes CSS规则里面,我们需要定义动画发生的阶段时间和变化样式。例如,0% 表示动画的开始阶段,100% 表示动画的结束时刻。animation属性里引用 keyframes 有一种简写方式,展开来一共有8个子属性,通过它们,我们可以控制各种的动画过程。

子属性

  • animation-name: 指定一个 @keyframes 的名称,动画将要使用这个@keyframes定义。
  • animation-duration: 整个动画需要的时长。
  • animation-timing-function: 动画进行中的时速控制,比如 easelinear.
  • animation-delay: 动画延迟时间。
  • animation-direction: 动画重复执行时运动的方向。
  • animation-iteration-count: 动画循环执行的次数。
  • animation-fill-mode: 设置动画执行完成后/开始执行前的状态,比如,你可以让动画执行完成后停留在最后一幕,或恢复到初始状态。
  • animation-play-state: 暂停/启动动画。

这些属性可以这样使用:

@keyframes stretch {
  /* declare animation actions here */
}

.element {
  animation-name: stretch;
  animation-duration: 1.5s; 
  animation-timing-function: ease-out; 
  animation-delay: 0;
  animation-direction: alternate;
  animation-iteration-count: infinite;
  animation-fill-mode: none;
  animation-play-state: running; 
}

/*
  等同于:
*/

.element {
  animation: 
    stretch
    1.5s
    ease-out
    0
    alternate
    infinite
    none
    running;
}

下面这个表格展示了每个子属性都可以使用哪些值:

animation-timing-function ease, ease-out, ease-in, ease-in-out, linear, cubic-bezier(x1, y1, x2, y2) (e.g. cubic-bezier(0.5, 0.2, 0.3, 1.0))
animation-duration Xs or Xms
animation-delay Xs or Xms
animation-iteration-count X
animation-fill-mode forwards, backwards, both, none
animation-direction normal, alternate
animation-play-state paused, running, running

多阶段动画

如果一个动画的起始状态和终止状态是一样的,那么,你可以用逗号分隔 0% 和 100% 的形式在 @keyframes 里声明:

@keyframes pulse {
  0%, 100% {
    background-color: yellow;
  }
  50% {
    background-color: red;
  }
}

多样动画

我们还可以一次声明多种动画效果,用逗号分隔。在下面的例子中,我们将会让圆圈的颜色发生变化,同时还会轻推它,让它来回移动。

.element {
  animation: 
    pulse 3s ease infinite alternate, 
    nudge 5s linear infinite alternate;
}

性能

CSS动画中的很多动画属性都需要关注执行性能,在使用一个动画前,你需要了解它的运行原理。然而,下面这些CSS动画技术的组合使用是很安全的,我们可以放心使用:

  • transform: translate()
  • transform: scale()
  • transform: rotate()
  • opacity

哪些CSS属性可以运用动画效果?

MDN 上有一个哪些CSS属性可以运用动画效果的清单。基本上,能够运用动画的属性都是颜色和数字值,而像 background-image 这样的属性就不具备动画特征。

阅读余下内容
 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注


京ICP备12002735号