如何在有溢出的 #panel-scroll 中延迟加载图像:scroll;我尝试了这个代码示例,但它给了我意外的令牌错误。谁能帮我解决这个问题吗?
document.addEventListener("DOMContentLoaded", function() {
var lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));
if ("IntersectionObserver" in getElementById('#panel-scroll') {
let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
lazyImage.srcset = lazyImage.dataset.srcset;
lazyImage.classList.remove("lazy");
lazyImageObserver.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
} else {
// Possibly fall back to event handlers here
}
});
我会考虑以下更新:
getElementById
时,不应使用“#”符号,因为这是不正确的。应该是:const scrollablePanel = document.getElementById('panel-scroll');
IntersectionObserver
的根作为选项:let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
...
}, { root: scrollablePanel });
document.addEventListener("DOMContentLoaded", function() {
const scrollContainer = document.querySelector('#panel-scroll');
const lazyImages = [...scrollContainer.querySelectorAll("img.lazy")];
if ("IntersectionObserver" in window) {
let observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
let img = entry.target;
img.src = img.dataset.src;
img.srcset = img.dataset.srcset;
img.classList.remove("lazy");
observer.unobserve(img);
}
});
}, { root: scrollContainer });
lazyImages.forEach(img => observer.observe(img));
} else {
// Fallback: Load all images if IntersectionObserver is not supported
lazyImages.forEach(img => {
img.src = img.dataset.src;
img.srcset = img.dataset.srcset;
});
}
});
作为根初始化
IntersectionObserver
。IntersectionObserver
的浏览器提供后备。仅当图像靠近可滚动
#panel-scroll
div 的视口时,此脚本才会有效地加载图像,从而增强性能和用户体验。