微博、新聞網站的評論區,往往採用「捲到底就自動載入更多」的無限捲動設計。本文示範如何以 jQuery 判斷是否已滾動到頁面底部,並在到達時透過 Ajax 載入下一批內容。
var stop = true;
$(window).scroll(function () {
totalheight = parseFloat($(window).height()) + parseFloat($(window).scrollTop());
if ($(document).height() <= totalheight) {
if (stop == true) {
stop = false;
$.post("ajax.php", { start: 1, n: 50 }, function (txt) {
$("#Loading").before(txt);
stop = true;
}, "text");
}
}
});
<div id="Loading">Loading...</div>
核心判斷是:把「視窗高度 + 已捲動距離」相加得到 totalheight,再與整份文件的總高度 $(document).height() 比較。當文件高度小於等於 totalheight,就代表已經捲到底部,這時便用 Ajax 向伺服器請求下一批資料,並用 before 把新內容插入到「Loading」提示之前。
stop 變數是個容易忽略卻很關鍵的設計。因為 Ajax 請求需要時間,若在這段等待期間使用者又觸發了幾次 scroll 事件,就會重複送出請求、造成重複載入。用 stop 做「鎖」,在請求開始時設為 false、完成後才設回 true,就能確保同一時間只有一個請求在跑,避免重複加載。這正是打造順暢無限捲動體驗的關鍵細節。