DIV CSS 佈局教程網

jQuery 偵測捲動到底部:ScrollDown 的基本判斷寫法
編輯:關於JavaScript     

「捲到頁面最底部時觸發某件事」是無限捲動、自動載入更多、顯示頁尾的共同基礎。用 jQuery 只要一個條件判斷就能完成。

一、基本範例

$(document).ready(function () {
    $(window).scroll(function () {
        if ($(window).scrollTop() ==
            $(document).height() - $(window).height()) {
            // 捲動條已經到底,在此處觸發
        }
    });
});

二、這個判斷式在說什麼

把它拆成三個量就很清楚:

  • $(window).scrollTop() —— 目前已經往上捲走的距離
  • $(document).height() —— 文件整體高度
  • $(window).height() —— 視窗(可見區域)高度

文件高度 − 視窗高度 就是「捲到最底時 scrollTop 的最大可能值」。兩者相等,代表已經到底。

三、為什麼建議不要用等號

實務上這個寫法有個隱患:捲動事件的觸發頻率與捲動速度有關,快速滾動時 scrollTop 很可能一次跳過頭,永遠碰不到那個精確的數字,於是條件永遠不成立。

改成「大於等於」並加上緩衝區,會穩健得多:

$(window).scroll(function () {
    var fromBottom = $(document).height() - $(window).scrollTop() - $(window).height();
    if (fromBottom <= 100) {   // 距離底部 100px 內就觸發
        loadMore();
    }
});

提前 100~200px 觸發,使用者感受不到等待,這也是各家內容站的標準做法。

四、加上「避免重複觸發」的旗標

若不加保護,在底部停留時每次捲動都會觸發一次,可能一次送出數十個請求:

var loading = false;

$(window).scroll(function () {
    var fromBottom = $(document).height() - $(window).scrollTop() - $(window).height();
    if (fromBottom <= 100 && !loading) {
        loading = true;
        $.ajax({
            url: "/api/list?page=" + (++page),
            success: function (res) {
                $("#list").append(res.html);
                loading = false;          // 完成後解鎖
            },
            error: function () {
                loading = false;          // 失敗也要解鎖,否則永遠卡住
                page--;
            }
        });
    }
});

失敗時記得也要把旗標復位,否則一次網路錯誤就會讓後續載入永久失效。

五、用 IntersectionObserver 更好

scroll 事件會在主執行緒上高頻觸發,容易成為效能瓶頸。現代做法是在列表底部放一個哨兵元素,讓瀏覽器在背景執行緒幫你偵測:

var sentinel = document.getElementById("sentinel");

var observer = new IntersectionObserver(function (entries) {
    if (entries[0].isIntersecting && !loading) {
        loading = true;
        fetch("/api/list?page=" + (++page))
            .then(function (r) { return r.text(); })
            .then(function (html) {
                document.getElementById("list").insertAdjacentHTML("beforeend", html);
                loading = false;
            });
    }
}, { rootMargin: "200px" });   // 提前 200px 進入就預先載入

observer.observe(sentinel);

rootMargin: "200px" 的效果等同前面「距離底部 100px」的緩衝,但完全不佔用主執行緒的捲動運算。

六、不用 jQuery 的原生寫法

window.addEventListener("scroll", function () {
    var fromBottom = document.documentElement.scrollHeight
                   - window.pageYOffset
                   - window.innerHeight;
    if (fromBottom <= 100) {
        console.log("到底了");
    }
}, { passive: true });

{ passive: true } 告訴瀏覽器這個監聽器不會呼叫 preventDefault(),讓捲動不必等待 JS 執行完,滑動會明顯順暢。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved