首页 > 解决方案 > 当 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);
}

标签: javascriptscrollscrollspyintersection-observer

解决方案


推荐阅读