<!DOCTYPE html>
<html>
<head>
<title>图片的懒加载</title>
<style>
* {
margin: 0;
padding: 0;
}
.container {
margin:0 auto;
800px;
}
.imgBox {
height: 430px;
margin-bottom: 20px;
overflow: hidden;
background-color: #eee;
}
.imgBox img {
display: none;
100%;
}
</style>
</head>
<body>
<div class="container">
<!-- <div class="imgBox"><img src="" alt="" data-img="./images/111.jpg"></div> -->
</div>
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="DelayImg.js"></script>
</body>
</html>
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let $container = $('.container'),
$imgBoxs = null,
$window = $(window);
// => 造点假数据 new Array(20).fill(null) 创建长度为20的数组,每项用 null 填充
let str = ``;
new Array(20).fill(null).forEach(item => {
str += `<div class="imgBox"><img src="" alt="" data-img="./images/111.jpg"></div>`;
});
$container.html(str);
$imgBoxs = $container.children('.imgBox');
// => 多张图片延迟加载
$window.on('load scroll', function () {
// => $B 获取浏览器底边框距离 body 的距离
let $B = $window.outerHeight() + $window.scrollTop();
// => 循环每一个图片区域,根据自己区域距离 body 的距离,计算出里面的图片是否加载
$imgBoxs.each((index, item) => {
let $item = $(item);
$itemA = $item.outerHeight() + $item.offset().top,
isLoad = $item.attr('isLoad');
if ($itemA <= $B && isLoad !== 'true') {
$item.attr('isLoad', true);
// => 加载当前区域中的图片
let $img = $item.children('img');
$img.attr('src', $img.attr('data-img'));
$img.on('load', () => $img.stop().fadeIn());
}
});
})