javascript - 当 Intersection 观察者在滚动上观察目标时
问题描述
我尝试使用 Intersection Observer API 实现 scrollspy 功能。因此,当目标部分通过视口底部时,固定标题中的列表应该是活动状态。当我向下滚动时,它就像我最初计划的那样运行良好,但向上滚动时却不能无缝运行。例如,当 section2 在视口底部通过不到其高度的一半,然后以其他方式滚动直到 section2 再次返回到视口底部,它应该激活第 1 部分,但它没有。有没有办法在交叉点观察者调用函数或任何条件语句中检测滚动方向来捕捉这种情况?
这是我在 JSBIN https://jsbin.com/budixapele/edit?html,css,js,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);
}
解决方案
推荐阅读
- git - Jenkins git 管道插件刚刚停止在第二个存储库签出上工作
- java - 无法在简单程序上解析符号“上下文”
- apache-kafka - Hbase中的数据类型转换
- ios - iOS 应用内订阅产品的价格是否要求与通过网站直接提供的类似产品的价格相同或更低?
- git - GitHub:抱歉,此差异不可用(已删除分叉)
- reactjs - React Native - 全局事件监听器
- c# - C# 如果整数对于 Int32 来说太大,我如何存储它并用它做数学运算
- javascript - 如果未在配置文件中设置实体目录,TypeORM 无法找到实体
- c - 使用 malloc 对结构进行数据对齐
- android - 按钮 OnclickListener 中的未定义箭头 - Android Studio