const imagez = document.querySelectorAll(".gallery__image");
const options = {
root: null,
rootMargin: "0px",
threshold: 0.7,
};
function handleImg(myImg, observer) {
myImg.forEach((myImgSingle) => {
console.log(myImgSingle.intersectionRatio);
if (myImgSingle.intersectionRatio > 0) {
loadImage(myImgSingle.target);
}
});
}
function loadImage(image) {
image.src = image.getAttribute("data-source");
}
const observer = new IntersectionObserver(handleImg, options);
imagez.forEach((img) => {
observer.observe(img);
});
imagez.forEach((img) => {
observer.unobserve(img);
});
观察者:不能实现观察者.unobserve(image); HTML
<img class="gallery__image" src="https://cdn.pixabay.com/photo/2018/09/13/10/36/mountains-3674334_1280.jpg" data-source="https://cdn.pixabay.com/photo/2018/09/13/10/36/mountains-3674334_1280.jpg" alt="Alpine Mountains" data-index="22">
不能正确实现observer.unobserve()。曾试着把它放在一个单独的函数中,但在这种情况下,我无法加载所有的图片。请解释一下我应该在我的代码中改变什么来停止观察。