html
<!DOCTYPE html>
<html>
<header>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.container {
margin: 0 auto;
width: 860px;
height: 224px;
}
.container .imgBox {
width: 100%;
height: 100%;
background: #ddd;
margin-bottom: 20px;
}
.container .imgBox img {
display: none;
}
</style>
</header>
<body>
<div class="container">
</div>
<script src="./node_modules/jquery/dist/jquery.min.js"></script>
<script src="./js/img.js"></script>
</body>
</html>
img.js
//获取container元素
let $container = $('.container')
let str = ''
//创建假数据用于测试,使用fill()填充为null
new Array(20).fill(null).forEach(item => {
str += `
<div class="imgBox">
<img src="" data-img="http://img95.699pic.com/photo/40005/2858.jpg_wh860.jpg"/>
</div>
`
})
//将数据添加到container节点中
$container.html(str)
//获取所有图片元素
let $imgBox = $container.children('.imgBox')
//同时绑定onload、onscroll事件
$(window).on('load scroll', function () {
//获取浏览器底部距离body的距离(滚动条距离+屏幕高度)
let scrollTop = $(window).scrollTop() + $(window).outerHeight()
//实现多个图片懒加载
$imgBox.each((index, item) => {
//由于item中为js对象,所以需要转换成jquery对象
let $item = $(item)
//获取当前图片距离body的位置(图片高度+距离body顶部的位置)
let currentTop = $item.outerHeight() + $item.offset().top
//获取img元素
let $img = $item.children('img')
//获取图片自定义属性isLoad
let isLoad = $img.attr('isLoad')
//如果滚动条滚动距离大于当前图片距离body顶部的位置,并且未加载过图片,就加载图片
if (scrollTop > currentTop && isLoad !== 'true') {
$img.attr('src', $img.attr('data-img'))
console.log($img)
$img.on('load', () => {
$img.stop().fadeIn()
})
//添加自定义属性isLoad,用于标识是否加载过图片,加载过就无需请求图片
$img.attr('isLoad', true)
}
})
})