無限捲動、回到頂端按鈕、捲動動畫等效果,前提都是「知道現在捲到哪裡」。jQuery 提供了幾個簡單方法就能取得這些數值。
$(document).height() // 整個頁面的總高度
$(window).height() // 目前瀏覽器視窗可見區域的高度,會隨視窗縮放而改變
$(document).scrollTop() // 垂直捲動距離,也就是視窗頂端距離頁面頂端多遠
關鍵區別在於:document 的高度是內容撐出來的,而 window 的高度是你眼前螢幕看得到的那塊。兩者相減,就是「最多能捲多遠」。
頂端最好判斷,捲動距離等於 0 就是頂:
if ($(document).scrollTop() == 0) {
// 已經在頁面最上方
}
if ($(document).scrollTop() >= $(document).height() - $(window).height()) {
// 已經捲到最底部
}
如果希望「快到底就先載入」,只要把右邊再扣掉一個緩衝值,例如 100px:
var closeToBottom = ($(window).scrollTop() + $(window).height() > $(document).height() - 100);
$(document).scrollLeft() // 取得水平捲動條的距離
$(document).scroll(function(){
$("#lb").text($(document).scrollTop());
})
<span id="lb" style="top:100px;left:100px;position:fixed;"></span>
這裡用 position:fixed 讓指示數字固定在畫面上,捲動時不會被帶走,方便觀察數值變化。
把上面的比值稍作轉換,就能做閱讀進度條:
$(window).on('scroll', function () {
var scrollTop = $(document).scrollTop();
var total = $(document).height() - $(window).height();
var percent = total > 0 ? (scrollTop / total) * 100 : 0;
$('#progress').css('width', percent + '%');
});