Element:scrollTop 屬性

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Element 介面的 scrollTop 屬性用於獲取或設定元素內容從其頂部邊緣滾動的畫素數。在現代瀏覽器中,此值是亞畫素精度的,這意味著它不一定是整數。

一個雙精度浮點值,表示元素當前從原點垂直滾動的畫素數,正值表示元素向下滾動(以顯示更多底部內容)。如果元素根本沒有上下滾動,則 scrollTop 為 0。如果文件不是活動文件,則返回值為 0。如果文件是在亞畫素精度裝置上渲染的,則返回值也是亞畫素精度的,可能包含小數部分。

如果元素可以從初始包含塊向上滾動,那麼 scrollTop 可能為負值。例如,如果元素的 flex-directioncolumn-reverse 並且內容向上增長,則當捲軸位於最底部位置(滾動內容的開頭)時,scrollTop0,然後隨著您滾動到內容末尾而變得越來越負。

Safari 會透過將 scrollTop 更新到最大滾動位置(除非停用了預設的“反彈”效果,例如透過將 overscroll-behavior 設定為 none)來響應過度滾動,而 Chrome 和 Firefox 則不會。例如,在 Safari 中,僅透過在元素已位於頂部時繼續向上滾動,scrollTop 就可能為負值。

可以設定 scrollTop 屬性,這將導致元素滾動到指定的垂直位置,其方式與使用具有 behavior: "auto"Element.scroll() 相同。

示例

滾動元素

在此示例中,嘗試滾動帶有虛線的邊框的容器,並觀察 scrollTop 值如何變化。

HTML

html
<div id="container">
  <p>
    Far out in the uncharted backwaters of the unfashionable end of the western
    spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this
    at a distance of roughly ninety-two million miles is an utterly
    insignificant little blue green planet whose ape-descended life forms are so
    amazingly primitive that they still think digital watches are a pretty neat
    idea.
  </p>
</div>

<div id="output">scrollTop: 0</div>

CSS

css
#container {
  overflow: scroll;
  height: 150px;
  width: 150px;
  border: 5px dashed orange;
}

#output {
  padding: 1rem 0;
}

JavaScript

js
const container = document.querySelector("#container");
const output = document.querySelector("#output");

container.addEventListener("scroll", (event) => {
  output.textContent = `scrollTop: ${container.scrollTop}`;
});

結果

規範

規範
CSSOM 檢視模組
# dom-element-scrolltop

瀏覽器相容性

另見