跳到主要内容

场景

2023年03月13日
柏拉文
越努力,越幸运

一、可视检测


1.1 核心

元素即将可见: threshold: 0

元素完全可见: threshold: 1

1.2 语法

const targetDom = document.querySelector(".box");
const intersectionObserverOption = {
threshold: 0,
};

function intersectionObserverCallback(entries, observer) {
entries.forEach((entry) => {
if (entry.isIntersecting) {
observer.unobserve(entry.target);
console.log("元素可见");
}
});
}

const intersectionObserver = new IntersectionObserver(
intersectionObserverCallback,
intersectionObserverOption
);
intersectionObserver.observe(targetDom);

二、图片懒加载


const lazyLoadImgList = document.querySelectorAll(".lazy-load-img");
const intersectionObserverOption = {
threshold: 0,
};

function loadImg(imgDom) {
const src = imgDom.getAttribute("data-src");
imgDom.src = src;
}

function intersectionObserverCallback(entries, observer) {
entries.forEach((entry) => {
if (entry.isIntersecting) {
observer.unobserve(entry.target);
loadImg(entry.target);
}
});
}

const intersectionObserver = new IntersectionObserver(
intersectionObserverCallback,
intersectionObserverOption
);
lazyLoadImgList.forEach((lazyLoadImg) => {
intersectionObserver.observe(lazyLoadImg);
});