Animate.css 可简化 CSS 动画编写,需引入 CDN 并添加 animate__animated 和 animate__xxx 类;支持样式控制持续时间、延迟、重复,以及 hover 和 Intersection Observer 触发。
用 Animate.css 能大幅简化 CSS 动画的编写,不用手写 keyframes、timing-function、duration 等细节,直接通过类名调用现成动画效果。
最简单的方式是通过 CDN 引入最新版(v4+):
v4 版本需配合 animate__animated 基础类使用,否则动画不生效。所有动画类名前缀统一为 animate__(如 animate__bounce)。
给元素添加两个类即可:
animate__fadeInUp、animate__rotateIn
例如:
滑入出现
不需要 JS 也能灵活调整动画行为:
style="anima
tion-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__ 类,需配合自定义规则)结合 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));