1 Star 1 Fork 1

feels/javascript基础

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
12、图片懒加载.html 1.84 KB
一键复制 编辑 原始数据 按行查看 历史
feels 提交于 2021-04-14 13:57 . 新增练习
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
img {
height: 200px;
display: block;
}
</style>
</head>
<body>
<img src="" data-src="https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png" alt="">
<img src="" data-src="https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png" alt="">
<img src="" data-src="https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png" alt="">
<img src="" data-src="https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png" alt="">
<img src="" data-src="https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png" alt="">
<img src="" data-src="https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png" alt="">
<img src="" data-src="https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png" alt="">
</body>
<script>
class Lazy {
constructor() {
this.imgList = document.querySelectorAll('img')
this.lazyLoad()
window.addEventListener('scroll', this.throttle(() => {
this.lazyLoad()
}, 200))
}
destroy() {
window.removeEventListener('scroll', this.throttle(() => {
this.lazyLoad()
}, 200))
}
throttle(fn, wait = 1000) {
let timer = null;
return function () {
if (!timer) {
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, wait)
}
}
}
lazyLoad() {
const H = document.documentElement.clientHeight;
const S = document.documentElement.scrollTop || document.body.scrollTop;
Array.from(this.imgList).forEach(img => {
if (H + S + 100 > img.offsetTop) {
console.log(4)
img.src = img.dataset.src
}
})
}
}
new Lazy()
</script>
</html>
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/liangbairong/basics-of-javascript.git
git@gitee.com:liangbairong/basics-of-javascript.git
liangbairong
basics-of-javascript
javascript基础
master

搜索帮助

D67c1975 1850385 1daf7b77 1850385