JS實現(xiàn)頁面數(shù)據(jù)無限加載
在手機(jī)端瀏覽網(wǎng)頁時,經(jīng)常使用一個功能,當(dāng)我們?yōu)g覽京東或者淘寶時,頁面滑動到底部,我們看到數(shù)據(jù)自動加載到列表。之前并不知道這些功能是怎么實現(xiàn)的,于是自己在PC瀏覽器上模擬實現(xiàn)這樣的功能。先看看瀏覽效果:
當(dāng)滾動條滾動到頁面底部時,提示“正在加載…”。
當(dāng)頁面已經(jīng)加載了所有數(shù)據(jù)后,滾動到頁面底部會提示“數(shù)據(jù)已加載到底了”:
實現(xiàn)數(shù)據(jù)無限加載的過程大致如下:
1.滾動條滾動到頁面底部。
2.觸發(fā)ajax加載,把請求返回的數(shù)據(jù)加載到列表后面。
如何判斷滾動條是否滾動到頁面底部?我們可以設(shè)置一個規(guī)則:當(dāng)滾動條的滾動高度和整個文檔高度相差不到20像素,則認(rèn)為滾動條滾動到頁面底部了:
文檔高度 - 視口高度 - 滾動條滾動高度 < 20
要通過代碼實現(xiàn)這樣的判斷,我們必須要了解上面的這些高度通過哪些代碼獲???可以參考我之前寫的一篇“HTML元素坐標(biāo)定位,這些知識點得掌握”。
上面的判斷,我封裝了一個方法:
//檢測滾動條是否滾動到頁面底部 function isScrollToPageBottom(){ //文檔高度 var documentHeight = document.documentElement.offsetHeight; var viewPortHeight = getViewportSize().h; var scrollHeight = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0; return documentHeight - viewPortHeight - scrollHeight < 20; }
判斷有了,我們就可以開啟一個定時器,900毫秒監(jiān)測一次,如果isScrollToPageBottom()返回true則調(diào)用ajax請求數(shù)據(jù),如果返回false則通過900毫秒之后再監(jiān)測。
下面是核心代碼實現(xiàn):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>無限分頁</title> <link rel="stylesheet" href="assets/css/index.css"/> </head> <body> <div class="l-page"> <ul id="list" class="list"> </ul> </div> <script src="http://cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script> <script src="js/jquery.mockjax.js"></script> <script type="text/javascript" src="js/dataMock.js"></script> <script type="text/javascript"> //作為一個對象的w和h屬性返回視口的尺寸 function getViewportSize(w){ //使用指定的窗口, 如果不帶參數(shù)則使用當(dāng)前窗口 w = w || window; //除了IE8及更早的版本以外,其他瀏覽器都能用 if(w.innerWidth != null) return {w: w.innerWidth, h: w.innerHeight}; //對標(biāo)準(zhǔn)模式下的IE(或任意瀏覽器) var d = w.document; if(document.compatMode == "CSS1Compat") return {w: d.documentElement.clientWidth, h: d.documentElement.clientHeight}; //對怪異模式下的瀏覽器 return {w: d.body.clientWidth, h: d.body.clientHeight}; } //檢測滾動條是否滾動到頁面底部 function isScrollToPageBottom(){ //文檔高度 var documentHeight = document.documentElement.offsetHeight; var viewPortHeight = getViewportSize().h; var scrollHeight = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0; return documentHeight - viewPortHeight - scrollHeight < 20; } //商品模板 function getGoodsTemplate(goods){ return "<li>" + "<div class='pic-wrap leftFloat'>" + "<img src='" + goods.pic + "'>" + "</div>" + "<div class='info-wrap leftFloat'>" + "<div class='info-name'><span>" + goods.name + "</span></div>" + "<div class='info-address'><span>" + goods.address +"</span></div>" + "<div class='info-bottom'>" + "<div class='info-price leftFloat'><span>¥" + goods.price + "</span></div>" + "<div class='info-star leftFloat'><span>" + goods.star + "人推薦</span></div>" + "<div class='info-more leftFloat'><span>更多信息</span></div>" + "</div>" + "</div>" + "</li>"; } //初始化的時候默給list加載100條數(shù)據(jù) $.ajax("http://localhost:8800/loadData?sessionId=" + (+ new Date)).done(function(result){ if(result.status){ var html = ""; result.data.forEach(function(goods){ html += getGoodsTemplate(goods); }); $("#list").append(html); } }); //加載數(shù)據(jù) function loadDataDynamic(){ //先顯示正在加載中 if( $("#loadingLi").length === 0) $("#list").append("<li id='loadingLi' class='loading'>正在加載...</li>"); else{ $("#loadingLi").text("正在加載...").removeClass("space"); } var loadingLi = document.getElementById("loadingLi"); loadingLi.scrollIntoView(); //加載數(shù)據(jù),數(shù)據(jù)加載完成后需要移除加載提示 var hasData = false, msg = ""; $.ajax("http://localhost:8800/loadData?sessionId=" + (+ new Date)).done(function(result){ if(result.status){ if(result.data.length > 0){ hasData = true; var html = ""; result.data.forEach(function(goods){ html += getGoodsTemplate(goods); }); $("#list").append(html); }else{ msg = "數(shù)據(jù)已加載到底了" } } $("#list").append(loadingLi); }).fail(function(){ msg = "數(shù)據(jù)加載失敗!"; }).always(function(){ !hasData && setTimeout(function(){ $(document.body).scrollTop(document.body.scrollTop -40); }, 500); msg && $("#loadingLi").text(msg); //重新監(jiān)聽滾動 setTimeout(watchScroll, 900); }); } //如果滾動條滾動到頁面底部,需要加載新的數(shù)據(jù),并且顯示加載提示 function watchScroll(){ if(!isScrollToPageBottom()){ setTimeout( arguments.callee, 900); return; } loadDataDynamic(); } //開始檢測滾動條 watchScroll(); </script> </body> </html>
demo中ajax請求我是通過jquery-mockjax模擬的數(shù)據(jù)。代碼如下:
/** * 模擬接口. */ var i = 0, len = 200, addresses = ["四川", "北京", "上海", "廣州", "深圳", "甘肅", "云南", "浙江", "青海", "貴州"]; function getData(){ var size = Math.min(i + 50, len), arr = []; for(; i < size; i++){ arr.push({ name: "蘋果" + (i % 10 + 1), pic: "assets/images/iphone" + (i % 10 + 1) + ".jpg", price: parseInt(Math.random() * 10000), star: parseInt(Math.random() * 1000), address: addresses[i % 10] }) } return arr; } $.mockjax({ url: 'http://localhost:8800/loadData*', responseTime: 1000, response: function(settings){ this.responseText = { status: true, data: getData() } } });
整個完整的demo我已上傳到github上:
https://github.com/heavis/pageLoader
在線演示:
https://heavis.github.io/pageLoader/index.html
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
30分鐘快速入門掌握ES6/ES2015的核心內(nèi)容(上)
ES6增加了很多新的語法,很多同學(xué)學(xué)習(xí)起來感覺很別扭,有時候也不理解新增加的語法有什么用,對ES6的學(xué)習(xí)也沒有興趣進(jìn)而動力不足、學(xué)習(xí)效率不高。下面這篇文章將通過30分鐘帶大家快速入門掌握ES6/ES2015的核心內(nèi)容,需要的朋友可以參考下。2018-04-04Javascript 檢測鍵盤按鍵信息及鍵碼值對應(yīng)介紹
Javascript中有3個事件句柄在對應(yīng)鍵盤的輸入狀態(tài):按鍵被按下(按下按鍵但還沒有抬起)、點擊按鍵(按下并抬起按鍵)、按鍵抬起(按鍵抬起之后),接下來詳細(xì)介紹,感興趣的朋友可以了解下2013-01-01