跳到主要内容

Scroll getBoundingClientRect

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(
boundingClientRect,
viewPortWidth,
viewProtHeight,
threshold
) {
const { top, right, bottom, left } = boundingClientRect;
if (threshold) {
return (
top >= 0 &&
left >= 0 &&
right <= viewPortWidth &&
bottom <= viewProtHeight
);
}
return (
top >= 0 &&
left >= 0 &&
right <= viewPortWidth &&
top <= viewProtHeight
);
}

function handleScroll() {
const viewPortWidth =
window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
const viewPortHeight =
window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;

const { length } = lazyLoadImgList;
for (let i = index; i < length; i++) {
const lazyLoadImgItem = lazyLoadImgList[i];
const boundingClientRect = lazyLoadImgItem.getBoundingClientRect();
if (
isVisible(boundingClientRect, viewPortWidth, viewPortHeight, true)
) {
const src = lazyLoadImgItem.getAttribute("data-src");
lazyLoadImgItem.src = src;
index++;
}
}
}

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