一篇文章搞懂css动画(二)

625 阅读3分钟

这是我参与11月更文挑战的第2天,活动详情查看:2021最后一次更文挑战

animation

animation 可以解决 上文中提到的 transition 问题的一种方式。

  1. 基本用法

首先,css animation 需要指定动画一个周期持续的时间,以及动画效果的名称

div:hover{
    animation:1s rainbow;
}

上面代码表示,当鼠标悬停在div元素上时,会产生名为rainbow的动画效果,持续时间为1秒。为此,我们还需要用keyframes关键字,定义rainbow效果。

@keyframes rainbow{
    0% {background:#c00;}
    50% {background : orange;}
    100% { background : yellowgreen;}
}

上面代码表示,rainbow效果一共有三个状态,分别为起始(0%)、中点(50%)和结束(100%)。如果有需要,完全可以插入更多状态。效果如下. 实例效果 默认情况下 ,动画只播放一次。加入infinite ,可以让动画无限次播放。

div:hover{
    animation: 1s rainbow infinite;
}

也可以指定动画具体播放次数,比如3次。

div:hover{
    animation :1s rainbow 3;
}

2. animation-fill-mode

动画结束以后,会立即从结束状态跳回到起始状态。如果想让动画保持在结束状态,需要使用animation-fill-mode属性。


forwards 表示可以让动画停留在结束状态.🔚

div:hover{
    animation: 1s rainbow forwards;
}

animation-fill-mode还可以使用下列值。

1none:默认值,回到动画没开始时的状态。

(2)backwards:让动画回到第一帧的状态。

(3)both: 根据animation-direction(见后)轮流应用forwards和backwards规则。

3. animation-direction

动画循环播放时,每次都是从结束状态跳回到起始状态,再开始播放。animation-direction属性,可以改变这种行为。

@keyframes rainbow {
  0% { background-color: yellow; }
  100% { background: blue; }
}

默认情况是,animation-drection 等于 normal。


div:hover {
  animation: 1s rainbow 3 normal;
}

此外,还可以等于取alternate、reverse、alternate-reverse等值。它们的含义见下图(假定动画连续播放三次)。

image.png

简单说,animation-direction指定了动画播放的方向,最常用的值是normal和reverse。浏览器对其他值的支持情况不佳,应该慎用。

4. animation 的各项属性

同transition 一样,animation也是一个 简写的形式

div:hover{
    animation:1s 1s rainbow linear 3 forwards normal;
}

div:hover {
  animation-name: rainbow;
  animation-duration: 1s;
  animation-timing-function: linear;
  animation-delay: 1s;
    animation-fill-mode:forwards;
  animation-direction: normal;
  animation-iteration-count: 3;
}

5. keyframes 的写法

keyframes 关键字用来定义动画的各个状态 ,他的写法相当自由。

@keyframes rainbow{
    0% {background:#c00}
    50%{background:orange}
    100% {background:yellowgreen}
    
}
//其中 0% 可以用from代表,100% 可以用 to代表,因此上面的代码 等同于下面这种形势

@keyframes rainbow{
    from   { background:#c00} 
    50%{background:orange}
    to{background:yellowgreen}
    
}
//甚至可以把多个状态写在一行。
@keyframes pound{
    from,to{transform:none;}
    50%{transform :scale(1.2);}
}

另外一点需要注意的是,浏览器从一个状态向另一个状态过渡,是平滑过渡。steps函数可以实现分步过渡。(雪碧图)的使用

div:hover{
    animation:1s rainbow infinite steps(10);
}

6 animation-play-state

有时,动画播放过程中,会突然停止。这时,默认行为是跳回到动画的开始状态。如果想让动画保持突然终止时的状态,就要使用animation-play-state属性。


div {
    animation: spin 1s linear infinite;
    animation-play-state: paused;
}

div:hover {
  animation-play-state: running;
}

7. 浏览器前缀

目前,IE 10和Firefox(>= 16)支持没有前缀的animation,而chrome不支持,所以必须使用webkit前缀。


div:hover {
  -webkit-animation: 1s rainbow;
  animation: 1s rainbow;  
}

@-webkit-keyframes rainbow {
  0% { background: #c00; }
  50% { background: orange; }
  100% { background: yellowgreen; }
}

@keyframes rainbow {
  0% { background: #c00; }
  50% { background: orange; }
  100% { background: yellowgreen; }
}

参考文章 阮一峰