返回課程

無限頁面

重要性:5

建立一個無限頁面。當訪客捲動到頁面底部時,它會自動將目前的日期時間附加到文字上(這樣訪客就可以捲動更多內容)。

就像這樣

請注意捲動的兩個重要特點

  1. 捲動是「有彈性的」。我們可以在某些瀏覽器/裝置上稍微捲動超過文件開頭或結尾(會顯示下方的空白,然後文件會自動「彈回」正常位置)。
  2. 捲動是不精確的。當我們捲動到頁面底部時,我們實際上可能距離真正的文件底部 0-50 像素。

因此,「捲動到底部」應表示訪客距離文件底部不超過 100 像素。

附註:在實際情況中,我們可能想要顯示「更多訊息」或「更多商品」。

開啟一個沙盒進行任務。

解決方案的核心是一個函式,當我們在頁面底部時,它會將更多日期新增到頁面(或在實際情況中載入更多內容)。

我們可以立即呼叫它,並將它新增為 window.onscroll 處理常式。

最重要的問題是:「我們如何偵測頁面已捲動到底部?」

讓我們使用相對於視窗的座標。

文件表示(並包含)在 <html> 標籤中,也就是 document.documentElement

我們可以取得整個文件相對於視窗的座標,方法是使用 document.documentElement.getBoundingClientRect()bottom 屬性會是文件底部相對於視窗的座標。

例如,如果整個 HTML 文件的高度是 2000px,那麼

// when we're on the top of the page
// window-relative top = 0
document.documentElement.getBoundingClientRect().top = 0

// window-relative bottom = 2000
// the document is long, so that is probably far beyond the window bottom
document.documentElement.getBoundingClientRect().bottom = 2000

如果我們向下捲動 500px,那麼

// document top is above the window 500px
document.documentElement.getBoundingClientRect().top = -500
// document bottom is 500px closer
document.documentElement.getBoundingClientRect().bottom = 1500

當我們捲動到最後,假設視窗高度是 600px

// document top is above the window 1400px
document.documentElement.getBoundingClientRect().top = -1400
// document bottom is below the window 600px
document.documentElement.getBoundingClientRect().bottom = 600

請注意,bottom 不能是 0,因為它永遠不會到達視窗頂端。bottom 座標的最低限制是視窗高度(我們假設它是 600),我們無法再向上捲動它。

我們可以取得視窗高度,方法是使用 document.documentElement.clientHeight

對於我們的任務,我們需要知道文件底部與它相距不超過 100px 的時候(也就是說:600-700px,如果高度是 600)。

所以,以下就是函式

function populate() {
  while(true) {
    // document bottom
    let windowRelativeBottom = document.documentElement.getBoundingClientRect().bottom;

    // if the user hasn't scrolled far enough (>100px to the end)
    if (windowRelativeBottom > document.documentElement.clientHeight + 100) break;

    // let's add more data
    document.body.insertAdjacentHTML("beforeend", `<p>Date: ${new Date()}</p>`);
  }
}

在沙盒中開啟解決方案。