在實現「滾動到底部自動加載」這類功能時,我們需要準確判斷頁面是否已經滑到底部。由於各瀏覽器對 documentElement 與 body 的支援不一致,必須做兼容處理。
下面的 reachBottom 函數綜合了多種情況,能較為可靠地判斷是否到達頁面底部:
function reachBottom() {
var scrollTop = 0;
var clientHeight = 0;
var scrollHeight = 0;
if (document.documentElement && document.documentElement.scrollTop) {
scrollTop = document.documentElement.scrollTop;
} else if (document.body) {
scrollTop = document.body.scrollTop;
}
if (document.body.clientHeight && document.documentElement.clientHeight) {
clientHeight = (document.body.clientHeight < document.documentElement.clientHeight)
? document.body.clientHeight : document.documentElement.clientHeight;
} else {
clientHeight = (document.body.clientHeight > document.documentElement.clientHeight)
? document.body.clientHeight : document.documentElement.clientHeight;
}
scrollHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
if (scrollTop + clientHeight == scrollHeight) {
return true;
} else {
return false;
}
}
關鍵在於三個量:scrollTop(已滾動距離)、clientHeight(可視區高度)與 scrollHeight(內容總高度)。當「已滾動距離 + 可視區高度」等於內容總高度時,即代表已經滑到底部。
透過取 Math.max 與條件判斷,這個函數能有效抹平不同瀏覽器之間的差異,是實現無限滾動加載的基礎判斷邏輯。