首页 > 解决方案 > IntersectionObserver:找出元素何时在视口之外

问题描述

使用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.

标签: javascriptintersection-observer

解决方案


您的代码中有两个问题:

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

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


推荐阅读