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

Animate.css如何实现元素滚动进入视口时触发动画效果

该需求完全可以实现,核心思路是先移除元素上默认挂载的animate.css动画类,通过 Intersection Observer API 监听元素进入可视区域的时机,再动态添加动画类触发效果。

步骤1:调整HTML代码

移除h2标签class属性中自带的animate__animated和动画效果类,改为通过自定义属性存储动画类,同时增加自定义标记类供JS识别需要滚动触发的动画元素:

<h2 class="lazyload scroll-animate" data-animate-class="animate__animated animate__rotateInDownLeft" data-link="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">Lorem ipsum</h2>

步骤2:添加视口监听逻辑

使用Intersection Observer API实现监听,该API是浏览器原生提供的异步监听接口,性能远优于传统的scroll事件绑定,不会造成页面滚动卡顿:

// 初始化观察者
const animateObserver = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    // 元素进入可视区域时触发
    if (entry.isIntersecting) {
      const targetEl = entry.target;
      // 读取存储的动画类添加到元素上
      const animateClass = targetEl.dataset.animateClass;
      targetEl.classList.add(...animateClass.split(' '));
      // 只需触发一次动画就取消监听,不需要重复触发可删除下行代码
      observer.unobserve(targetEl);
    }
  })
}, {
  // 阈值设为0.1表示元素露出10%时触发动画,可按需调整
  threshold: 0.1
})

// 给所有需要滚动触发动画的元素绑定监听
document.querySelectorAll('.scroll-animate').forEach(el => {
  animateObserver.observe(el);
})

如果需要实现元素每次滚动进入可视区域都重新播放动画,可取消observer.unobserve(targetEl)代码,同时在添加动画类前先移除原有动画类、强制重排触发重置即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:15:03