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

Hel*_*esh 5 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);
Run Code Online (Sandbox Code Playgroud)

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

str*_*str 4

您的代码中有两个问题:

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

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