DIV CSS 佈局教程網

jQuery 中 document、window、scrollTop 三種高度怎麼算
編輯:JQuery特效代碼     

三個基本方法

$(document).height()   // 整個網頁的高度
$(window).height()     // 瀏覽器可視窗口的高度
$(window).scrollTop()  // 可視窗口頂端距網頁頂端的距離(垂直捲動量)

一句話記住關係

當捲軸拉到最底端時:

$(document).height() == $(window).height() + $(window).scrollTop()

這個等式是很多捲動效果的基礎。例如「捲到底就載入更多」的判斷就是:

$(window).scroll(function () {
    if ($(window).scrollTop() + $(window).height() >= $(document).height() - 50) {
        loadMore();   // 距離底部還剩 50px 時就觸發
    }
});

內容不足一頁時

當網頁高度不足以撐滿瀏覽器窗口時,$(document).height() 回傳的值會等於 $(window).height(),而不是實際內容的高度。這在寫「是否捲到底」的判斷時要留意,否則可能在頁面根本沒有捲軸的情況下誤觸。

不建議使用的寫法

避免使用 $("html").height() 與 $("body").height(),原因如下:

$("body").height():body 可能有 margin 或 border,取得的高度會比 $(document).height() 小。若內容的最後一個元素有 margin-bottom,它也可能落在 body 之外,導致數值偏小。

$("html").height():在不同瀏覽器上,html 元素高度的意義有差異。部分瀏覽器把它當成內容高度,部分當成視窗高度,說白了就是跨瀏覽器不相容。

$(window).height():這個通常沒問題,回傳的就是視窗可視區域高度。若遇到數值異常,檢查一下是不是被 CSS transform 縮放影響,或是否在 iframe 內被父層縮放。

相關方法補充

$(window).width()            // 視窗寬度
$(document).width()          // 文件寬度
$(window).scrollTop(val)     // 設定捲動位置
$("body").scrollTop()        // 部分瀏覽器需讀 body,跨瀏覽器時可兩者都設
$(window).innerHeight()      // 含 padding、不含 border 與捲軸
$(window).outerHeight()      // 含 padding 與 border

實務上建議把「取得文檔高度」封裝成一個函式,統一取 $(document).height(),避免專案裡到處散落各種寫法而難以除錯。

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