1

我尝试在我的 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);
    });
 }

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

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

4

2 回答 2

1

也许这也有效:

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

"如果你不检查 intersectingRatio ratio === 1,观察到的元素将触发两次回调,因为当立即通过/离开 100% 阈值时,观察者将触发 isIntersecting = true, intersectionRatio ~= 0.9(可能是错误)。Chrome 不知何故在第一个框上得到的 intersectionRatio 略高于 1,因此将该值设置为

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

于 2020-11-30T20:11:05.290 回答
0

我通过删除 ngOnInit() 解决了这个问题,因为它在加载后再次触发 ngAfterViewInit()。

于 2019-10-22T09:28:36.173 回答