【发布时间】:2023-04-06 17:18:01
【问题描述】:
情况
我在页面顶部有一个固定的导航栏。当您向下滚动浏览页面的不同部分时,导航栏会动态更新(下划线和突出显示)。您也可以单击导航栏上的某个部分,它会向下滚动到该部分。
这是使用交叉点观察者 API 来检测它所在的部分并使用 scrollIntoView 滚动到每个部分来完成的。
问题
假设您在第 1 部分,然后单击最后一个部分 5,它会将页面向下滚动到中间的所有其他部分。滚动速度很快,并且当它滚动时,交叉点观察器会检测到所有部分,因此会更新导航。当每个导航项经过每个相应的部分时,您最终会获得导航快速变化的效果。
目标
如果该部分仅在帧中一毫秒,您如何延迟交叉点观察者触发菜单更改?快速滚动时,导航栏应仅在滚动停止某个部分后更新。
代码设置
const sectionItemOptions = {
threshold: 0.7,
};
const sectionItemObserver = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
// select navigation link corresponding to section
} else {
// deselect navigation link corresponding to section
}
});
}, sectionItemOptions);
// start observing all sections on page
sections.forEach((section) => {
sectionItemObserver.observe(section);
});
想法
我的第一个想法是设置一个 setTimeout 以便导航在超时完成之前不会改变,然后如果该部分在超时完成之前离开屏幕,则取消超时。但是由于超时在 forEach 循环中,这不起作用。
const sectionItemObserver = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
let selectNavTimeout
if (entry.isIntersecting) {
// Set timeout when section is scrolled past
selectNavTimeout = setTimeout(() => {
// select navigation link corresponding to section
}, 1000)
} else {
// deselect navigation link corresponding to section
// cancel timeout when section has left screen
clearTimeout(selectNavTimeout)
}
});
}, sectionItemOptions);
任何其他想法将不胜感激!谢谢:)
【问题讨论】:
标签: javascript settimeout intersection-observer