JS clientHeight,scrollHeight,offsetHeight,scrollTop,offsetTop概念
//是否进入可视区域
function isInsight(el) {
const bound = el.getBoundingClientRect();
const windowHeight = window.innerHeight();
return bound.top <= windowHeight ;
}
//用index标识已经加载过的图片,滚动条滚动时只需遍历未加载过的图片
let index = 0;
function checkImg() {
const imgs = document.querySelectorAll(".my-photo");
for(let i = index; i<imgs.length; i++ ) {
if(inInsight) {
loadImg(imgs[i]);
index = i;
}
}
}
function loadImg(el) {
if(!el.src){
el.src = el.dataSet.src;
}
}
函数节流
function throttle(fn, interval = 300) {
let canRun = true;
return function () {
if (!canRun) return;
canRun = false;
setTimeout(() => {
fn.apply(this, arguments);
canRun = true;
}, interval);
};
}
页面代码
<img src="" data-src="xxx"/>
<img src="" data-src="xxx"/>
<img src="" data-src="xxx"/>
<img src="" data-src="xxx"/>
<script>
window.onload = checkImgs;
window.onscroll = throttle(checkImgs)
</script>