← 中文资源

简体中文版本

IntersectionObserver 滚动侦测高亮

用窄条 rootMargin 把视口中部变成侦测带,谁跨进高亮带谁就是当前小节;命中后同步 classList 与 aria-current,滚动侦测只需一个观察器。

阅读英文原文

实现说明

IntersectionObserver 滚动侦测高亮的核心是函数 setActive。 结构是循环套循环:for (const section of sections) 在外,for (const [key, link] of links) 在内。

使用要点

  • document、IntersectionObserver 只存在于浏览器——Node 运行时没有现成的垫片。
  • 每一步打印都带着自己的标签:scroll spy observing。

常见问题

「IntersectionObserver 滚动侦测高亮」能在裸 Node.js 里跑吗?

不能——document、IntersectionObserver 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。

主签名形如 function setActive(id: string)

核心语句

link.textContent = section.querySelector('h2')?.textContent ?? section.id;
.sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);
setActive(sections[0]?.id ?? '');

代码示例

// Scroll spy: a narrow rootMargin band in the middle of the viewport
// decides which section currently counts as "read"
const sections = [...document.querySelectorAll('main section[id]')];
const links = new Map<string, HTMLAnchorElement>();
const nav = document.querySelector('nav');

for (const section of sections) {
  const link = document.createElement('a');
  link.href = '#' + section.id;
  link.textContent = section.querySelector('h2')?.textContent ?? section.id;
  nav?.append(link);
  links.set(section.id, link);
}

function setActive(id: string): void {
  for (const [key, link] of links) {
    link.classList.toggle('active', key === id);
    link.setAttribute('aria-current', key === id ? 'true' : 'false');
  }
}

const observer = new IntersectionObserver(
  (entries) => {
    const visible = entries
      .filter((entry) => entry.isIntersecting)
      .sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);
    if (visible.length > 0) setActive(visible[0].target.id);
  },
  // only the middle band of the viewport triggers highlighting
  { rootMargin: '-40% 0px -55% 0px' },
);

for (const section of sections) observer.observe(section);
setActive(sections[0]?.id ?? '');
console.log('scroll spy observing', sections.length, 'sections');