Animate.css 可简化 CSS 动画编写,需引入 cdn 并添加 animate__animated 和 animate__xxx 类;支持样式控制持续时间、延迟、重复,以及 hover 和 Intersection Observer 触发。

用 Animate.css 能大幅简化 CSS 动画的编写,不用手写 keyframes、timing-function、duration 等细节,直接通过类名调用现成动画效果。
引入 Animate.css 库
最简单的方式是通过 CDN 引入最新版(v4+):
href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css”>
v4 版本需配合 animate__animated 基础类使用,否则动画不生效。所有动画类名前缀统一为 animate__(如 animate__bounce)。
基础用法:两步触发动画
给元素添加两个类即可:
- animate__animated —— 必须加,提供基础动画重置和 display 处理
- animate__xxx —— 选一个动画效果,比如
animate__fadeInUp、animate__rotateIn
例如:
常用控制技巧
不需要 js 也能灵活调整动画行为:
- 修改持续时间:
style="animation-duration: 2s;" - 调整延迟开始:
style="animation-delay: 0.5s;" - 控制重复次数:
style="animation-iteration-count: 3;"或infinite - 鼠标悬停触发动画:用
:hover组合,如.box:hover .animate__animated {animation-name: animate__swing; }(注意 v4 不支持 hover 直接加 animate__ 类,需配合自定义规则)
进阶:配合 JS 实现滚动触发动画
结合 Intersection Observer,让元素进入视口时才播放动画,避免 一加 载就全动:
给目标元素加上 data-animate="animate__zoomIn",然后用几行 JS 监听并动态添加类即可:
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add(‘animate__animated’, entry.target.dataset.animate);
observer.unobserve(entry.target);
}
});
});
document.querySelectorAll(‘[data-animate]’).forEach(el => observer.observe(el));