如何使用Animate.css实现元素滚动到视图时触发动画?
用Animate.css实现滚动到视口才触发动画
实现思路
通过自定义属性标记需要动画的元素,结合滚动监听(或更高效的IntersectionObserver)检测元素是否进入视口,一旦进入就为元素添加Animate.css的动画类,同时处理初始隐藏状态和动画只触发一次的逻辑。
步骤1:引入资源
确保页面中已引入Animate.css:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
步骤2:HTML结构
给目标元素添加自定义属性指定动画类型,同时加初始类控制默认状态:
<div class="animate-on-scroll" data-animate="fadeInUp"> <!-- 内容 --> </div> <div class="animate-on-scroll" data-animate="zoomIn"> <!-- 内容 --> </div>
步骤3:基础CSS
设置元素初始不可见,避免动画前突兀显示:
.animate-on-scroll { opacity: 0; visibility: hidden; transition: opacity 0.2s ease-out, visibility 0.2s ease-out; } .animate-on-scroll.animated { opacity: 1; visibility: visible; }
步骤4:JavaScript逻辑(两种方案)
方案A:滚动监听(兼容旧浏览器)
document.addEventListener('DOMContentLoaded', function() { const animatedElements = document.querySelectorAll('.animate-on-scroll'); function checkElements() { animatedElements.forEach(el => { if (el.dataset.animated === 'true') return; const rect = el.getBoundingClientRect(); // 元素上下边缘进入视口内20px时触发 const isVisible = rect.top < window.innerHeight - 20 && rect.bottom > 20; if (isVisible) { const animationClass = el.dataset.animate; el.classList.add('animated', animationClass); el.dataset.animated = 'true'; } }); } checkElements(); window.addEventListener('scroll', checkElements); window.addEventListener('resize', checkElements); });
方案B:IntersectionObserver(性能更优,现代浏览器支持)
document.addEventListener('DOMContentLoaded', function() { const observerOptions = { root: null, rootMargin: '0px 0px -20px 0px', // 元素底部进入视口20px触发 threshold: 0.1 // 元素10%可见时触发 }; const observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { const el = entry.target; const animationClass = el.dataset.animate; el.classList.add('animated', animationClass); observer.unobserve(el); } }); }, observerOptions); document.querySelectorAll('.animate-on-scroll').forEach(el => { observer.observe(el); }); });
注意事项
- 可调整
rootMargin或滚动监听的阈值,控制动画触发时机 - Animate.css支持的动画类可参考官方文档选择,如
fadeIn、slideInLeft等 - 若需要重复触发动画,可去掉
dataset.animated标记或unobserve逻辑
内容的提问来源于stack exchange,提问作者Mahfouz
相关产品推荐
相关产品推荐

