问题描述
我尝试使用 Intersection Observer API 实现滚动监视功能。因此,当目标部分通过视口底部时,固定标题中的列表应该是活动状态。当我向下滚动时,它按照我最初的计划运行良好,但在向上滚动时它不能无缝地工作。例如,当第 2 部分在视口底部通过不到其高度的一半,然后以另一种方式滚动,直到第 2 部分再次回到视口底部,它应该激活第 1 部分,但它没有。有没有办法在交叉观察者调用函数或任何条件语句中检测滚动方向来捕捉这种情况?
这是我在 JSBIN 的简要实现 https://jsbin.com/budixapele/edit?html,output
const headerHeight = document.querySelector('header').offsetHeight;
const paragraphSection = document.querySelectorAll('section');
const menuList = document.querySelectorAll('header nav li');
const intersectionCallback = (entries) => {
if (entries[0].intesectionRatio <= 0) return;
entries.forEach(entry => {
let target = entry.target.id;
const navItem = document.querySelector('a[href*=' + target +
']');
if (entry.isIntersecting) {
menuList.forEach((el) => {
el.classList.remove('active');
});
navItem.closest('li').classList.add('active');
history.pushState(null,null,`#${target}`);
} else {
navItem.closest('li').classList.remove('active');
}
});
}
const intersectionoptions = {
rootMargin: '-91px 0px 0px 0px',threshold: 0
};
const intersectionObserver = new IntersectionObserver(
intersectionCallback,intersectionoptions
);
for (const section of paragraphSection) {
intersectionObserver.observe(section);
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)