本文示範一個仿微博風格的無限滾動效果:當滾動條接近頁面底部時,會自動、無刷新地從後台加載新數據並追加到列表末尾。
實現的關鍵在於監聽 window 的 scroll 事件,判斷是否接近頁腳,並用一個標誌位 isOK 防止上一次 ajax 尚未完成時重複觸發。
<style type="text/css">
body{ font-family: "Trebuchet MS",verdana,arial;}
#loading{ display:none; font-weight:bold;color:#FF0000;}
p { padding:10px;}
</style>
<p id="loading">loading data... </p>
$(function(){
var isOK=true;//記錄上次訪問是否已經結束
var scrollH=0;//判斷是往上滾還是往下滾
var intI=1;
$(".loading").css({"right":"2","bottom":0});
$(".loading")
.ajaxStart(function(){
isOK=false;//執行ajax的時候把isOK設置成false防止重複執行
$("#loading2").show();
})
.ajaxStop(function(){
isOK=true;
$("#loading2").hide();
})
$(window).scroll(function(){
//觸法ajax條件
if($(document).height()-$(window).scrollTop()-document.documentElement.clientHeight<240){
//當前位置比上次的小就是往上滾動不要執行ajax代碼塊
if(scrollH>document.documentElement.scrollTop) {
$(".loading").append("<br/>向上滾不執行")
scrollH=document.documentElement.scrollTop;
return;
}
if(isOK)//如果是第一次或者上次執行完成了就執行本次
{
scrollH=document.documentElement.scrollTop;
isOK=false;
$.ajax({
type:"POST",
dataType: 'xml',
url:"https://localhost:49302/MY100/2010/WebService1.asmx/getDS",
error:function(e){
$(".main").append('發生了錯誤:'+e)
},
success:function(data){
try{
$(data).find("Table").each(function(i){
$(".main").append("結果:"+$(this).children('txtTitle').text()+"<br/>");
$(".main").append("結果:"+$(this).children('txtBody1').text()+"<br/>");
})
} catch(e){
$(".main").append("<p>"+e+"</p>")
}
}
})
}
}
})
})
核心邏輯是:透過 $(document).height()-$(window).scrollTop()-clientHeight < 240 判斷是否接近頁腳,並用 scrollH 記錄位置以區分向上或向下滾動,配合 isOK 標誌位避免重複請求,从而實現平滑的无限下拉加载效果。
希望本文所述對大家 jQuery 程序設計有所幫助。