跳到主要内容

Scroll OffsetTop OffsetHeight

2024年06月18日
柏拉文
越努力,越幸运

一、认识


二、实现


let index = 0;
const lazyLoadImgList = document.querySelectorAll(".lazy-load-img");

function throttle(fn, wait) {
let timer = null;
return function (...args) {
const context = this;
if (!timer) {
timer = setTimeout(() => {
clearTimeout(timer);
timer = null;
fn.apply(context, args);
}, wait);
}
};
}

function isVisible(
viewPortHeight,
viewportScrollTop,
targetDomOffsetTop
) {
return viewPortHeight + viewportScrollTop >= targetDomOffsetTop;
}

function handleScroll() {
const viewPortHeight =
window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
const viewportScrollTop =
document.documentElement.scrollTop ||
window.pageYOffset ||
document.body.scrollTop;
const { length } = lazyLoadImgList;
for (let i = index; i < length; i++) {
const lazyLoadImgItem = lazyLoadImgList[i];
if (
isVisible(
viewPortHeight,
viewportScrollTop,
lazyLoadImgItem.offsetTop
)
) {
const src = lazyLoadImgItem.getAttribute("data-src");
lazyLoadImgItem.src = src;
index++;
}
}
}

handleScroll();
window.addEventListener("scroll", throttle(handleScroll, 80));