使用IntersectionObserver API无法为元素添加类的问题排查
滚动动画失效问题排查
问题描述
跟随FireShip的滚动动画教程操作后,JavaScript代码无法正常工作:页面仅显示黑屏,h1元素无法通过透明度变化逐步显示,排查发现元素进入视口时,无法通过classList.add()为h1元素添加类。
所用代码
HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Cool Scrolls</title> <link rel="stylesheet" href="style.css"> <script differ src="script.js"></script> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet"> </head> <body> <section> <h1 class="hide">Introducing</h1> </section> <section> <h1 class="hide">The One And Only</h1> </section> <section> <h1 class="hide">"Hello World"</h1> </section> </body> </html>
CSS代码
* { font-family: "Roboto", sans-serif; background-color: black; } section { display: flex; justify-content: center; align-items: center; color: white; min-height: 100vh; font-size: 3em; } .hide { opacity: 0; transition: all 1s; } .show { opacity: 1; }
JavaScript代码
const observer = new IntersectionObserver((entries) => { entries.forEach((entry) => { if (entry.isIntersecting) { entry.target.classList.add('show'); } else { entry.target.classList.remove('show'); } }); }); const hiddenElements = document.querySelectorAll('.hide'); hiddenElements.forEach((el) => observer.observe(el));
问题原因及解决方法
核心问题
HTML中script标签的属性拼写错误:differ应该是defer。这个错误导致JavaScript代码在DOM还未完全加载时就执行了,此时document.querySelectorAll('.hide')无法获取到页面中的h1元素,IntersectionObserver也就没有绑定到任何元素上,自然不会触发类的添加操作。
修复方案
- 修正script标签属性:将
<script differ src="script.js"></script>改为<script defer src="script.js"></script>,defer属性会让JS脚本在DOM加载完成后再执行,确保能正确获取到所有.hide元素。 - 备选方案:将script标签移动到body标签的末尾(
</body>之前),同样能保证DOM加载完成后再执行JS代码。
内容的提问来源于stack exchange,提问作者Samuel Tamba
相关产品推荐
相关产品推荐

