我对IntersectionObserver API很陌生,我一直在试验这段代码:
let target = document.querySelector('.lazy-load');
let options = {
root: null,
rootMargin: '0px',
threshold: 0
}
let observer = new IntersectionObserver(callback, options);
observer.observe(target);
function callback() {
console.log('observer triggered.');
}
这似乎可以正常工作,并且在元素进入视口callback()
时被调用,但在页面最初加载时也会触发一次,这会触发 `console.log('observer trigger.');.lazy-load
callback()
页面加载时是否有理由触发此回调?或者我如何实施这个有错误?
编辑:将代码更改为以下代码仍会在页面加载时触发回调。
let target = document.querySelector('.lazy-load');
let options = {
root: null,
rootMargin: '0px',
threshold: 0
}
let callback = function(entries, observer) {
entries.forEach(entry => {
console.log('observer triggered.');
});
};
let observer = new IntersectionObserver(callback, options);
observer.observe(target);