我尝试在我的 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,则会引发错误,因为它不是节点列表???