Animate.css 基本用法

Animate.css 是一个轻量级、跨浏览器的 CSS 动画库,内置了几十种预设动画(如弹跳、淡入淡出、翻转、滑动等),无需编写复杂的 @keyframes,只需添加 class 即可快速为元素添加动画效果,适合快速提升页面交互体验。

一、安装与引入

1. CDN 引入(推荐,最简单)

直接在 HTML 中引入 CDN 链接(以最新版为例):

1
<link rel="stylesheet" href="https://unpkg.com/animate.css@4.1.1/animate.min.css">

2. npm 安装

适合工程化项目:

1
npm install animate.css --save

然后在项目中引入:

1
import 'animate.css';

二、基本用法

Animate.css 的动画 class 分为两部分:

  • 基础 classanimate__animated(必须加,用于初始化动画)
  • 动画 classanimate__xxx(具体动画效果,如 animate__bounce

示例:给元素添加弹跳动画

1
2
3
<div class="animate__animated animate__bounce">
我会弹跳!
</div>

三、常用预设动画分类

Animate.css 提供了丰富的动画效果,以下是常用分类及示例:

分类 常用动画 class 效果说明
注意力吸引 animate__bounce(弹跳) 元素上下弹跳
animate__pulse(脉冲) 元素轻微放大缩小
animate__shakeX(左右抖动) 元素左右摇晃
淡入动画 animate__fadeIn(淡入) 从透明到不透明
animate__fadeInUp(向上淡入) 从下方淡入
animate__fadeInDown(向下淡入) 从上方淡入
滑入动画 animate__slideInLeft(左滑入) 从左侧滑入
animate__slideInRight(右滑入) 从右侧滑入
缩放动画 animate__zoomIn(放大进入) 从小放大到正常大小
animate__zoomOut(缩小退出) 从正常大小缩小到消失
翻转动画 animate__flipInX(X轴翻转进入) 沿水平轴翻转进入
animate__flipInY(Y轴翻转进入) 沿垂直轴翻转进入

四、高级用法:控制动画细节

Animate.css 提供了辅助 class,可控制动画的延迟、速度、重复次数

1. 动画延迟(animate__delay-*

让动画延迟一段时间后执行,支持 1-5 秒:

1
2
3
<div class="animate__animated animate__bounce animate__delay-2s">
2秒后才开始弹跳
</div>

2. 动画速度(animate__slow/fast

调整动画持续时间:

  • animate__slow:2秒(默认1秒)
  • animate__slower:3秒
  • animate__fast:800毫秒
  • animate__faster:500毫秒
1
2
3
<div class="animate__animated animate__bounce animate__slow">
慢动作弹跳
</div>

3. 动画重复次数(animate__repeat-*

控制动画重复播放次数,或无限循环:

  • animate__repeat-1/2/3:重复1-3次
  • animate__infinite:无限循环
1
2
3
<div class="animate__animated animate__bounce animate__infinite">
一直弹跳不停歇
</div>

五、结合 JavaScript 动态触发动画

通过 JS 动态添加/移除 class,可实现“点击触发动画”“滚动触发动画”等效果。

示例:点击按钮触发动画

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<div id="box" style="width: 100px; height: 100px; background: red;"></div>
<button id="btn">点击让方块弹跳</button>

<script>
const box = document.getElementById('box');
const btn = document.getElementById('btn');

btn.addEventListener('click', () => {
// 先移除之前的动画 class(避免无法重复触发)
box.classList.remove('animate__animated', 'animate__bounce');

// 强制重绘(让浏览器重新识别 class 添加)
void box.offsetWidth;

// 重新添加动画 class
box.classList.add('animate__animated', 'animate__bounce');
});
</script>

示例:监听动画结束事件

1
2
3
4
box.addEventListener('animationend', () => {
console.log('动画播放完毕!');
// 可在这里移除动画 class 或执行其他操作
});

六、注意事项

  1. Class 前缀:Animate.css v4+ 版本的所有 class 都以 animate__ 开头(两个下划线),避免与其他 CSS 类冲突。
  2. 性能优化:避免同时给大量元素添加复杂动画(如 animate__flip),可能导致页面卡顿。
  3. 浏览器兼容性:支持所有现代浏览器(Chrome、Firefox、Safari、Edge),IE10+ 也能基本兼容。
  4. 自定义动画:如果预设动画不满足需求,可结合 CSS 变量覆盖默认配置(如 --animate-duration 自定义时长):
    1
    2
    3
    .my-custom-animation {
    --animate-duration: 0.5s; /* 自定义动画时长为0.5秒 */
    }

Animate.css 基本用法
https://cszy.top/2014-12-26 animate-css/
作者
csorz
发布于
2014年12月26日
许可协议