0
点赞
收藏
分享

微信扫一扫

JS使用lazyload进行图片懒加载

原理:
方法:
引用
  <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/jquery_lazyload/1.9.7/jquery.lazyload.js"></script>
//html
<div>
<ul>
<li><img data-original="https://xxxxxxcity.jpg" src="https://xxxxxxloading.gif" alt="" width="600px" height='480px'></li>
<li><img data-original="https://xxxxxxcity.jpg" src="https://xxxxxxloading.gif" alt="" width="600px" height='480px'></li>
<li><img data-original="https://xxxxxxcity.jpg" src="https://xxxxxxloading.gif" alt="" width="600px" height='480px'></li>
<li><img data-original="https://xxxxxxcity.jpg" src="https://xxxxxxloading.gif" alt="" width="600px" height='480px'></li>
<li><img data-original="https://xxxxxxcity.jpg" src="https://xxxxxxloading.gif" alt="" width="600px" height='480px'></li>
</ul>
</div>
//js
$('ul img').lazyload()

这样就完成了最简易的图片懒加载了

可自行拓展延伸
<script>
//后端分页进行滚动加载
$(function () {
var pageNo = 1, //页码
pageSize = 10; //条数
imgLists(pageNo); //获取数据
$(window).scroll(function () { //滚动条事件
var scrollTop = Math.ceil($(this).scrollTop()); //滚动条与页面高度 //小数点原因 向上取整
var curHeight = $(this).height(); //可视区域高度
var totalHeight = $(document).height(); //页面总高度
if (scrollTop + curHeight >= totalHeight) { //滚动条触底加载
imgLists(pageNo++)
}
})
//获取数据 1.引用jQuery、jquery.lazyload 2.img中固定写法 data-original 3.$('ul li img').lazyload();
function imgLists(pageNo) {
$.ajax({
type: 'get',
url: '192.168.0.999:8080/home/page/' + pageNo + '/' + pageSize,
dataType: 'json',
success: function (res) { //成功
$.each(res, function (index, item) {
$('ul').append(
`<li>
<img data-original='${item.img}' src='https://xxxxxxloading.gif' height='480px' width='600px'>
</li>`
)
})
//懒加载
$('ul img').lazyload();

},
error: function (res) { //失败

},
})
}
})
</script>
举报

相关推荐

0 条评论