對於樓層加載在以前只是個想法,從來沒實現過,剛好項目中碰到,再此總結一下
場景:HTML5,局部商品列表信息滾動(局部滾動條)
1.通過jq設置subCategoryScroll的高度為屏幕顯示高度(假設為100),設置productlist的高度為列表信息的實際高度(假設為300)
<div id="subCategoryScroll" style="overflow: hidden; overflow-y: scroll;"> <ul class="list-inline mb0 ml0" id="productlist"> <li>商品信息區域</li> </ul> </div>
2.滾動腳本,實現如果拉到最底部,將加載下一頁顯示;往回滾,不觸發加載事件(重點)
var page = 1;//加載的索引 var isload = true;//設置是否終止滾動加載 var curScrollHeight = 0;//當前滾動位置 var curCount = 1;//計數器,防止滾動時重復執行加載下一頁 $("#subCategoryScroll").scroll(function () { var pageHeight = $("#productlist").height(); var showHeight = $("#subCategoryScroll").height(); var scrollHeight = $("#subCategoryScroll").scrollTop(); if (curScrollHeight - scrollHeight < 10 && curScrollHeight>0) { if (curCount == 1) { page += 1; loadproducts(page); //加載新數據 } curCount++; //加載下一頁后計數器+1 } if (curScrollHeight < scrollHeight) { curScrollHeight = pageHeight - showHeight;//滾動到頁面底部時,重設當前滾動位置 curCount = 1; } }); function loadproducts(pageindex) { $.ajax({ url: $("#GetDataUrl").val(), data: { "currentPageIndex": pageindex, "Condition": $("#Condition").val() }, type: 'GET', dataType: 'json', timeout: 10000, async: false, success: function (resultData) { if (resultData != null) { var html = ""; if (resultData.rows == 0 && pageindex == 1) { isload = false; html = "抱歉,暫無商品!" $("#productlist").append(html); } else { $.each(resultData.rows, function (i, item) { html = '<li>內容</li>'; $("#productlist").append(html); }); if (resultData.PageTotal == pageindex) { isload = false; } } } } }); }
整體不難,關鍵在於滾動事件的邏輯處理
如果是頁面body的滾動條,pageHeight、showHeight、scrollHeight 與 $(document).height()、 $(window).height() 、 $(document).scrollTop()一一對應