小编vcx*_*gfx的帖子

IntersectionObserver 不适用于长段 JS 的小屏幕

此脚本为活动部分发出活动类。最近注意到它在小屏幕上停止工作。即使在 chrome 的开发人员控制台中,我也会开始增加屏幕尺寸并且它会出现,一旦我开始缩小它就会立即停止工作(活动类消失)。但仅对于一个长部分,在较短的部分中一切正常。如何解决这个问题?

在代码片段中,我设置了一个较大的固定高度,因此投资组合链接不会接收活动类,在我的示例中,当部分宽度增加时,其高度会减小,因此在某些时候一切都会开始工作。

const links = document.querySelectorAll('.nav-link');
const sections = [... document.querySelectorAll('.forJS')];

const callback = (entries) => {
  links.forEach((link) => link.classList.remove('active'));
  const elem = entries.find((entry) => entry.isIntersecting);
  if (elem) {
    const index = sections.findIndex((section) => section === elem.target);
    links[index].classList.add('active');
  }
}

let observer = new IntersectionObserver(callback, {
  rootMargin: '0px',
  threshold: 0.5
});

sections.forEach((section) => observer.observe(section));
Run Code Online (Sandbox Code Playgroud)
section {
  height: 100vh;
  scroll-y: auto;
}
.long{
height: 300vh;
}
.nav-link.active{
  color: red;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<body>
<header class="fixed-top">
  <nav …
Run Code Online (Sandbox Code Playgroud)

javascript ecmascript-6 intersection-observer

7
推荐指数
1
解决办法
363
查看次数