You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何结合JavaScript实现Animate.css滚动触发动画

用Intersection Observer结合Animate.css实现视口触发动画

这是目前最标准、性能最优的实现方案,替代传统的scroll事件监听,避免频繁触发重绘:

步骤1:元素标记

给需要延迟触发动画的元素添加一个自定义标识类(比如animate-on-scroll),同时指定Animate.css的动画类,但不要加animate__animated(这个类是触发动画的核心类,提前加会导致页面加载时就执行):

<div class="animate-on-scroll animate__fadeIn">视口触发淡入动画</div>
<p class="animate-on-scroll animate__bounceInUp">视口触发上弹动画</p>

步骤2:JavaScript逻辑

使用Intersection Observer API检测元素是否进入视口,触发时添加animate__animated类启动动画:

// 配置Observer选项:rootMargin可以设置提前触发的距离(比如提前100px进入视口就触发)
const observerOptions = {
  root: null, // 使用视口作为根元素
  rootMargin: '0px 0px -50px 0px', // 元素底部进入视口50px时触发
  threshold: 0.1 // 元素10%进入视口时触发
};

// 定义触发动画的回调函数
const animateOnScroll = (entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      // 添加Animate.css的核心动画类
      entry.target.classList.add('animate__animated');
      // 动画只触发一次,触发后停止观察该元素
      observer.unobserve(entry.target);
    }
  });
};

// 创建Observer实例
const observer = new IntersectionObserver(animateOnScroll, observerOptions);

// 选择所有需要触发的元素并开始观察
document.querySelectorAll('.animate-on-scroll').forEach(el => {
  observer.observe(el);
});

额外优化

  • 如果需要动画结束后保留样式,不用额外处理;如果需要重置,可以监听animationend事件移除类,但一般场景不需要
  • 若要支持极旧浏览器(比如IE11),可以引入Intersection Observer的polyfill(直接在项目中引入即可,无需修改现有逻辑)
  • 可通过调整rootMargin和threshold参数,精准控制动画触发的时机

内容的提问来源于stack exchange,提问作者Brian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 11:08:15