需要的依赖 jquery.js、jquery.lazyload.js
项目结构:
|------app
|------|--------js
|-----|------jquery.js
|-----|-----jquery.lazyload.js
|----index.html
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title></title>
<link rel="stylesheet" type="text/css" href="css/common.css">
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/jquery.lazyload.js"></script>
<script src="js/index.js"></script>
<body>
<!--页面容器-->
<div class="index-content">
<div class="banner">
<img src="img/banner.jpg">
</div>
<div class="index-main">
<p>商品秒杀</p>
<ul>
<!--<li class="lists">
<img src="img/1.jpg" width="150" height="150">
<label>
<b class="discount">¥ 329</b>
<span class="price-text">¥ 379</span>
</label>
</li>-->
</ul>
</div>
</div>
</body>
</html>
$(function(){
//第一种方式 第三方插件实现
// $.ajax({
// type:'get',
// url:'http://127.0.0.1:3333/home',
// dataType:'json',
// success:function(res){
// console.log(res);
// if(res.length>0){
// $.each(res,function(index,item){
// $(".index-main ul").append('<li class="lists"> '+
// '<img data-original="'+item.product_img_url+'" src="img/loading.gif" width="150" height="150">'+
// '<label>'+
// '<b class="discount">'+item.product_uprice+'</b>'+
// '<span class="price-text">'+item.product_price+'</span> '+
// '</label> '+
// '</li>')
// })
// };
// //懒加载
// $(".index-main ul img").lazyload({
// effect:'fadeIn' //淡入效果
// })
// },
// error:function(error){
// console.log(error);
// }
// });
imgList();
//第二种方式
$(window).scroll(function(){
//滚动条与顶部的距离
var scrollTop = Math.ceil($(this).scrollTop());
//当前可视区域的高
var h = $(this).height();
//页面的总高度
var top = $(document).height();
// console.log(scrollTop);
if(scrollTop + h >= top) { //滚动条触底
imgList();
}
})
});
function imgList() {
$.ajax({
type:'get',
url:'http://127.0.0.1:3333/home',
dataType:'json',
success:function(res){
console.log(res);
//截图10条
var data = res.slice(0,10);
if(data.length>0){
$.each(data,function(index,item){
$(".index-main ul").append('<li class="lists"> '+
'<img src="'+item.product_img_url+'" width="150" height="150">'+
'<label>'+
'<b class="discount">'+item.product_uprice+'</b>'+
'<span class="price-text">'+item.product_price+'</span> '+
'</label> '+
'</li>')
})
};
},
error:function(error){
console.log(error);
}
});
}