【问题标题】:Avoid Intersection Observer to observe 2 targets at time避免交叉路口观察者一次观察 2 个目标
【发布时间】:2021-05-16 04:49:31
【问题描述】:

我的页面中有一些部分和一些导航链接。我使用 Intersection Observer 将 active 类添加到重定向到此部分的相应链接。在我页面的某些部分,有 2 个部分是可见的,我想将 active 类添加到最明显的部分(一次仅一次),但我不知道如何:

这里是 Intersection Observer 代码:

    const sectObserver = new IntersectionObserver(entries => {
    for (entry of entries) {
      // here i get the section id and the link classList:
      const { id } = entry.target,
      { classList } = document.querySelector(`#to-${id}`);
      if (entry.intersectionRatio) {
        classList.add('active');
      } else {
        classList.remove('active');
      };
    };
  });

这里是目标观察者的实例:

    document.querySelectorAll('section:not(#get-cv, #skills)')
      .forEach(link => sectObserver.observe(link));

【问题讨论】:

    标签: javascript html intersection-observer


    【解决方案1】:

    Intersection Observer 有一个threshold 选项,它定义了在运行您的函数之前需要看到多少部分(从 0 到 1)。尝试为您页面上的部分设置正确的百分比。

    const options = { threshold: 0.5 };
    const sectObserver = new IntersectionObserver(entries => {
      for (entry of entries) {
        // here i get the section id and the link classList:
        const { id } = entry.target,
        { classList } = document.querySelector(`#to-${id}`);
        if (entry.intersectionRatio) {
          classList.add('active');
        } else {
          classList.remove('active');
        };
      };
    }, options);
    

    【讨论】:

      猜你喜欢
      • 2018-11-22
      • 2022-11-17
      • 1970-01-01
      • 2023-04-06
      • 2022-01-18
      • 2022-01-17
      • 2021-07-20
      • 1970-01-01
      相关资源
      最近更新 更多