如何使用CSS制作动画效果 | 第三方库介绍以及animate.css的简单使用

1,067 阅读2分钟

这是我参与8月更文挑战的第27天,活动详情查看:8月更文挑战

轮子

一个很重要的的准则:不要重复造轮子

CSS制作动画从代码上来说并不简单,每个动画效果都涉及到许多参数,要达到合适的动画效果需要断地调整动画参数,如动画时常,动画帧的切分,动画调速函数等等。 而大多数人使用的动画效果其实就那么几样,比如抖动,震荡等等,相比我们每个人都从头书写动画,是否有人将常用动画总结起来让大家使用过呢。

有的!

我在网上找到的几个列在这里:

现成的动画库

  1. animate.css 最著名的动画库;
  2. magic.css 项目首页我表示没看懂,点击没效果;
  3. Vivify animate.css的增强版
  4. Effect.css
  5. hover.css hover效果动画;
  6. wickedCSS
  7. three-dots 三个点的动画效果演示,很有意思
  8. csshake 抖动的动画效果合集

可视化制作CSS动画——动画生成器

  1. animista.net/
  2. angrytools

下面我们来看看animate.css如何在自己的项目中使用。

如何使用animate.css

以无框架HTML+CSS为例。

如下列代码与图所示,我们首先绘制一个淡蓝色的方块。

<!DOCTYPE html>
<head>
    <title>animate.css使用测试</title>
  </head>
  <body>
      <div class="box"></div>
  </body>
  <style>
      .box {
          width: 300px;
          height: 300px;
          background: lightblue;
      }

  </style>
</html>

初步效果图:

image.png

引入资源文件

<head>
  <link
    rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"
  />
</head>

给指定对象添加类

我们需要给指定对象添加两个类:

  1. animate__animated
  2. animate__xxx, 其中xxx表示如bounceflash等等

比如,我们添加animate__animated animate__bounce,动画效果如下所示:

动画.gif

恩,有效果!我们换一个效果更明显的:animate__hinge

动画.gif

NICE JOB!!

代码很简单,以上全部代码如下:

<!DOCTYPE html>
<head>
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"
    />
    <title>animate.css使用测试</title>
  </head>
  <body>
      <div class="box animate__animated animate__hinge"></div>
  </body>

  <style>
      body {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: center;
      }
      .box {
          width: 300px;
          height: 300px;
          background: lightblue;
      }
  </style>
</html>

在animate.css官网,详细介绍了animate.css的其他允许的配置,比如动画延迟时间,动画播放次数等等都可以通过简单的代码来实现。

恩,我再也不用担心自己不会实现设计师莫名其妙的动画效果了!