JS實現(xiàn)頁面數(shù)據(jù)無限加載
在手機端瀏覽網(wǎng)頁時,經(jīng)常使用一個功能,當我們?yōu)g覽京東或者淘寶時,頁面滑動到底部,我們看到數(shù)據(jù)自動加載到列表。之前并不知道這些功能是怎么實現(xiàn)的,于是自己在PC瀏覽器上模擬實現(xiàn)這樣的功能。先看看瀏覽效果:
當滾動條滾動到頁面底部時,提示“正在加載…”。
當頁面已經(jīng)加載了所有數(shù)據(jù)后,滾動到頁面底部會提示“數(shù)據(jù)已加載到底了”:

實現(xiàn)數(shù)據(jù)無限加載的過程大致如下:
1.滾動條滾動到頁面底部。
2.觸發(fā)ajax加載,把請求返回的數(shù)據(jù)加載到列表后面。
如何判斷滾動條是否滾動到頁面底部?我們可以設(shè)置一個規(guī)則:當滾動條的滾動高度和整個文檔高度相差不到20像素,則認為滾動條滾動到頁面底部了:
文檔高度 - 視口高度 - 滾動條滾動高度 < 20
要通過代碼實現(xiàn)這樣的判斷,我們必須要了解上面的這些高度通過哪些代碼獲?。靠梢詤⒖嘉抑皩懙囊黄癏TML元素坐標定位,這些知識點得掌握”。
上面的判斷,我封裝了一個方法:
//檢測滾動條是否滾動到頁面底部
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ù)則使用當前窗口
w = w || window;
//除了IE8及更早的版本以外,其他瀏覽器都能用
if(w.innerWidth != null)
return {w: w.innerWidth, h: w.innerHeight};
//對標準模式下的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)文章
用javascript實現(xiàn)div可編輯的常見方法
用javascript實現(xiàn)div可編輯的常見方法...2007-10-10
JS?解決Cannot?set?properties?of?undefined的問題
遇到這樣問題當前的是當前對象或者數(shù)組是undefined,但是卻用來引用屬性或者索引,遇到這樣的問題如何解決呢,下面通過本文給大家介紹JS?如何解決Cannot?set?properties?of?undefined,需要的朋友可以參考下2024-01-01
JavaScript面試必備之垃圾回收機制和內(nèi)存泄漏詳解
垃圾回收機制和內(nèi)存泄漏是JavaScript面試時常常問到的問題,這篇文章就為大家詳細整理了他們的相關(guān)知識,感興趣的小伙伴可以跟隨小編一起了解一下2023-05-05
一文詳解如何將Javascript打包成exe可執(zhí)行文件
這篇文章主要介紹了將Javascript打包成exe可執(zhí)行文件的相關(guān)資料,這種方法適用于需要將JavaScript項目打包成單個獨立運行的可執(zhí)行文件的開發(fā)者,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2025-04-04
javascript實現(xiàn)倒計時關(guān)閉廣告
這篇文章主要為大家詳細介紹了javascript實現(xiàn)倒計時關(guān)閉廣告,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-02-02

