IntersectionObserver:找出元素何时在视口之外

时间:2019-05-12 13:51:46

标签: javascript intersection-observer

使用IntersectionObserver API,如何确定特定元素何时在视口之外?

一旦用户滚动经过标题,因此标题不再位于视口内,我就需要输出控制台日志。我想使用IntersectionObserver而不是滚动事件侦听器来最小化负载,因为它异步工作。到目前为止,我的代码是:

let options = {
   root: null, //root
   rootMargin: '0px',
   threshold: 1.0,
 };

 function onChange(changes, observer) {
    changes.forEach(change => {
       if (change.intersectionRatio < 0) {
          console.log('Header is outside viewport');
        }
    });
  }

  let observer = new IntersectionObserver(onChange, options);

  let target = document.querySelector('#header');
  observer.observe(target);

此代码不输出任何控制台日志。 PS:我的<header>元素的ID为header

1 个答案:

答案 0 :(得分:1)

您的代码中有两个问题:

  • 您的options.threshold被定义为“ 1”。这意味着onChange总是在intersectionRatio从值<1变为1时执行,反之亦然。但是,您真正想要的是threshold为“ 0”。

  • intersectionRatio永远不会低于0。因此,您必须将if子句中的条件更改为change.intersectionRatio === 0

相关问题