エンドレスページ
エンドレスページを作成してください。訪問者がページの一番下までスクロールすると、現在の日付と時刻がテキストに自動的に追加されます(これにより、訪問者はさらにスクロールできます)。
このように
スクロールの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
の場合、600〜700px
)を知る必要があります。
これが関数です。
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>`);
}
}