無限捲動、自動載入更多內容,這類功能的第一步都是同一件事:判斷使用者有沒有滑到底。而這件事只需要三個 DOM 屬性就能完成。
scrollTop:捲動條在 Y 軸上已經捲過的距離。
clientHeight:內容可視區域的高度,也就是視口高度。
scrollHeight:內容可視區域高度加上溢出的部分,即整份文件的總高度。
三者一擺出來,條件就非常清楚:當 scrollTop + clientHeight == scrollHeight 時,捲動條剛好抵達底部。
為了相容不同瀏覽器(尤其是需要同時考慮 document.body 與 document.documentElement 的舊版 IE),通常會包裝成三個取值函數:
// 捲動條在 Y 軸上的捲動距離
function getScrollTop(){
var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
if (document.body){ bodyScrollTop = document.body.scrollTop; }
if (document.documentElement){ documentScrollTop = document.documentElement.scrollTop; }
scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
return scrollTop;
}
// 文件的總高度
function getScrollHeight(){
var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
if (document.body){ bodyScrollHeight = document.body.scrollHeight; }
if (document.documentElement){ documentScrollHeight = document.documentElement.scrollHeight; }
scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
return scrollHeight;
}
// 瀏覽器視口的高度
function getWindowHeight(){
var windowHeight = 0;
if (document.compatMode == "CSS1Compat"){
windowHeight = document.documentElement.clientHeight;
} else {
windowHeight = document.body.clientHeight;
}
return windowHeight;
}
window.onscroll = function(){
if (getScrollTop() + getWindowHeight() == getScrollHeight()){
alert("you are in the bottom!");
}
};
有了 jQuery,同樣的判斷只要三行:
$(window).scroll(function(){
var scrollTop = $(this).scrollTop();
var scrollHeight = $(document).height();
var windowHeight = $(this).height();
if (scrollTop + windowHeight == scrollHeight){
alert("you are in the bottom");
}
});
把判斷結果換成「 append 幾筆資料」,就是最經典的延遲載入:
<!doctype html>
<html lang="en" style="height:900px;">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/lazyload.css" />
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<title>lazyLoad</title>
<script type="text/javascript">
$(function(){
var $ul = $("#lazyLoadWrap").find("ul");
$(window).scroll(function(){
var scrollTop = $(this).scrollTop();
var scrollHeight = $(document).height();
var windowHeight = $(this).height();
if (scrollTop + windowHeight == scrollHeight){
for (var i = 0; i < 6; i++){
$ul.append("<li>Hello</li>");
}
}
});
});
</script>
</head>
<body>
<div id="lazyLoadWrap">
<ul>
<li></li><li></li><li></li><li></li>
<li></li><li></li><li></li><li></li>
</ul>
</div>
</body>
</html>
用等號比對浮點數或像素值有時會因為小數誤差永遠不成立,實務上常改成 >= 更保險。另外,每一次捲動都觸發請求會對伺服器造成壓力,通常會再加一個「是否正在載入」的旗標與節流處理,等請求結束後才允許下一次觸發。