路口观察者在 ngAfterViewInit 上触发回调两次

Ram*_*Ram 4 javascript typescript angular intersection-observer

我尝试在我的 Angular 7 应用程序中使用 Intersection Observable 延迟加载图像。我从 ngAfterViewInit 生命周期钩子中调用了 Intersection Observable。但是当我加载应用程序时,回调被调用两次,一次所有 isIntersecting 值都为 true,下一次调用正确的 isIntersecting 值。我对这种行为感到困惑。

ngAfterViewInit() {
const imgOne = document.querySelectorAll('[data-class]');

    const options = {
      // root: document
      // threshold: 0
    };

    const observer = new IntersectionObserver((entries, observer) => {
      console.log(entries.length);
      entries.forEach((entry) => {
        // console.log(entry);
        if (!entry.isIntersecting) {
          return;
        } else {
          const el = entry.target;
          if (el.id === ('test' + this.testCount)) {
            console.log(entry);
          }
          // observer.unobserve(entry.target);
        }
      });
    });

    imgOne.forEach((eachQuery) => {
      observer.observe(eachQuery);
    });
 }
Run Code Online (Sandbox Code Playgroud)

https://stackblitz.com/edit/angular-wqbuyr

更新:现在交叉观察器被完美调用,但现在出现了问题。由于我们使用 document.querySelectorAll 返回静态节点列表,因此一旦数组更新,节点列表就不会更新。如果我尝试使用 document.getElementsByClassName,则会抛出错误,因为它不是节点列表???

Was*_*aga 5

也许这也有效:

if (entry.isIntersecting && Math.floor(entry.intersectionRatio) === 1) { 
  const el = entry.target;
  if (el.id === ('test' + this.testCount)) {
    console.log(entry);
  }
} else {
  return;
}
Run Code Online (Sandbox Code Playgroud)

如果你不'检查intersectionRatio比率===1,被观察的元素将触发回调两次,因为当立即通过/离开100%阈值时,观察者将触发isIntersecting = true,intersectionRatio〜= 0.9(可能是bug)。Chrome以某种方式在第一个框中得到的 junctionRatio 略高于 1,因此将值取底

来源: https: //codepen.io/mmanney/details/erpZbd