使用IntersectionObserver监听视口时元素移出后无法删除类问题排查
代码存在的3个核心问题
- 对
isIntersecting属性的判断逻辑错误:该属性是布尔类型,仅存在true/false两个值,你用数值比较entry.isIntersecting > 0、entry.isIntersecting === 0的写法不符合API规范,判断逻辑会出现异常。 - 移除类的操作对象错误:你在else分支中调用
sections.classList.remove,而sections是所有待监听元素的集合,不是当前触发移出事件的单个元素,同时分支中用到的section变量未定义,根本找不到对应的操作目标。 - 多余的取消监听操作:你在移出分支中调用了
observer.unobserve(section),会导致元素第一次移出视口后就被移除监听,后续再进入视口也不会触发任何回调,不符合你需要反复监听进出的需求。
修正后可正常运行的代码
const options = { threshold: 0.75, // 元素可见比例达到75%时触发进入回调,低于75%触发移出回调,可按需调整 } const observer = new IntersectionObserver(function (entries, observer) { entries.forEach(entry => { if (entry.isIntersecting) { entry.target.classList.add("StyleSection"); console.log(entry.target); } else { entry.target.classList.remove("StyleSection"); console.log(entry.target); } }); }, options); // 需保证前面已正确获取sections集合,例如const sections = document.querySelectorAll('你要监听的元素选择器') sections.forEach(section => { observer.observe(section); });
内容的提问来源于stack exchange,提问作者Youssef Salah Zakaria
相关产品推荐
相关产品推荐

