滚动渐入动画
滚动渐入是 JS 特效里使用率最高的一个:元素滚进视口时播放进场动画(上浮淡入、左滑、缩放)。标准实现是 IntersectionObserver,比死监听 scroll 性能高一个量级。
原理:观察元素与视口的交叉状态,isIntersecting 为真时加 .in 类,CSS .in 上定义终态(opacity:1/transform:0),进入类之前定义初态与 transition。
- 初态:opacity:0 + translateY(30px);.in 类恢复终态
- IntersectionObserver threshold 0.1~0.2:露 10% 即触发
- 执行一次就 unobserve,避免重复触发
HTML
<style> #scrolldemo { height: 200px; overflow: auto; padding: 10px; } .fadex { min-height: 90px; margin: 8px 0; border-radius: 10px; background: linear-gradient(135deg,#d2a8ff,#4a9eff); color: #fff; display: flex; align-items: center; justify-content: center; opacity: 0; transform: translateY(36px); transition: opacity .6s ease, transform .6s ease; } .fadex.in { opacity: 1; transform: none; } </style> <p style="color:#888;text-align:center">在这个小框里滚动 ↓</p> <div id="scrolldemo"> <div class="fadex">块 1</div><div class="fadex">块 2</div> <div class="fadex">块 3</div><div class="fadex">块 4</div> <div class="fadex">块 5</div><div class="fadex">块 6</div> </div> <script> var box = document.getElementById('scrolldemo'); if ('IntersectionObserver' in window) { var io = new IntersectionObserver(function (es) { es.forEach(function (e) { if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); } }); }, { root: box, threshold: 0.15 }); document.querySelectorAll('.fadex').forEach(function (el) { io.observe(el); }); } else { document.querySelectorAll('.fadex').forEach(function (el) { el.classList.add('in'); }); } </script>
本节要点滚动渐入 = IntersectionObserver + 初态/.in 终态 + 播一次 unobserve。




