【问题标题】:Intersection Observer - highlight current sectionIntersection Observer - 突出显示当前部分
【发布时间】:2018-12-12 16:01:15
【问题描述】:

每当部分部分可见或部分不可见时,我都会尝试激活和停用导航栏项目的类。如果我完全向下或向上滚动页面,代码可以正常工作。问题是如果我在一个部分的中间改变方向。

似乎该部分需要首先 100% 不在视野范围内,然后才能重新进入视野才能激活或停用课程(我相信会发生这种情况,因为我们正在检查 entry.isIntersecting 是否为真,并且它首先需要改为false)。尽管如此,这会导致不希望的行为。

我试过摆弄 if 语句来检查 entry.intersectionRatio,但我似乎也无法让它工作。为了以防万一,我也尝试过不同的浏览器,但行为仍然相同。

我该如何解决这个问题?

这里有一些code 显示了这种“错误”行为。它看起来像这样:

const sections = document.querySelectorAll('div.screen');
const config = {
  rootMargin: '-50px 0px -55%'
};

let observer = new IntersectionObserver(function (entries, self) {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      intersectionHandler(entry); 
    }
  });
}, config);

sections.forEach(section => {
  observer.observe(section);
});

function intersectionHandler(entry) {
  const id = entry.target.id;
  const currentlyActive = document.querySelector('nav li.active');
  const shouldBeActive = document.querySelector('nav li[data-ref=' + id + ']');

  if (currentlyActive) {
    currentlyActive.classList.remove('active');
  }
  if (shouldBeActive) {
    shouldBeActive.classList.add('active');
  }
}

codepen 来自this 文章。

提前致谢。

【问题讨论】:

    标签: navbar viewport highlight sections intersection-observer


    【解决方案1】:

    我一直在使用您的 CodePen,并找到了解决问题的方法。

    主要思想是确保同时只有一个元素可以在root 中。为此,您需要做两件事:

    首先,rootMargin 的高度应该尽可能的薄。

    rootMargin: '-45% 0px -55%'
    

    第二件事是为您的.screen CSS 类添加边距。

      margin-top: 3px;
    

    (1 或 2 px 可能太小)

    该代码在 Firefox 和 Chrome 上运行良好,但在似乎没有实现 InstersectionObserver API 的 Safari 上无法运行。我没有 Windows,所以无法测试 Edge 和 IE。

    【讨论】:

      【解决方案2】:

      您必须在观察者选项中明确定义您的根,因为您的演示在 iframe 中运行,否则会忽略 rootMargin。然后使用rootMargin 使观察者的高度尽可能小。

      const config = { 
         root: document,
         rootMargin: '-50% 0 -50%'
      }
      

      【讨论】:

        猜你喜欢
        • 2021-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-05
        • 2023-02-19
        • 2021-04-07
        相关资源
        最近更新 更多