上一篇文章介绍了实现图片懒加载的第一种方式:图片到浏览器顶部的距离
offsetTop
< 视口高度clientHeight
+滚动轴距离scrollTop
。 下面介绍实现懒加载的第二种方式,经过getBoundingClientRect
这个API
实现。html
getBoundClientRect
介绍Element.getBoundingClientRect() 方法返回元素的大小及其相对于视口的位置。咱们能够取得它的
top
值,它的top
值就是元素左上角到视口顶部的距离。git
当
Element.getBoundingClientRect().top
< 视口高度时触发加载;github
html
结构和CSS
样式<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
img {
height: 450px;
display: block;
margin-bottom: 20px;
}
</style>
</head>
<body>
<!--图片地址暂时先保存在data-src这个自定义属性上面-->
<img data-src="./img-loop/img/1.jpg" alt="懒加载1" />
<img data-src="./img-loop/img/2.png" alt="懒加载2" />
<img data-src="./img-loop/img/3.jpg" alt="懒加载3" />
<img data-src="./img-loop/img/4.jpg" alt="懒加载4" />
<img data-src="./img-loop/img/5.jpg" alt="懒加载5" />
</body>
</html>
复制代码
js
代码const imgs = document.getElementsByTagName('img');
// 判断元素是否出如今视口内
function isShow(el) {
// 视口高度
const clientH = window.innerHeight;
const bound = el.getBoundingClientRect();
// 判断元素左上角到视口顶部的距离是否小于视口高度
return bound.top < clientH;
};
// 加载图片
function showImg(el) {
if(!el.src) {
el.src = el.dataset.src;
}
}
// 懒加载
function lazyLoad() {
console.log('加载了');
[...imgs].forEach(el => {
if(isShow(el)) {
showImg(el);
}
})
};
lazyLoad();
// 节流函数
function throttle(fn, delay) {
let timer = null;
return () => {
if(timer) {
return;
};
timer = setTimeout(() => {
fn(imgs);
timer = null;
}, delay);
}
};
window.onscroll = throttle(lazyLoad, 500);
复制代码
所有代码浏览器
下一篇:懒加载的第三种实现方式bash