Element: scroll() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

Element 介面的 scroll() 方法可以將元素滾動到指定元素內的一組特定座標。

語法

js
scroll(xCoord, yCoord)
scroll(options)

引數

xCoord

希望顯示在左上角的元素水平軸的畫素值。

yCoord

希望顯示在左上角的元素垂直軸的畫素值。

options

包含以下屬性的物件:

top

指定要滾動視窗或元素的 Y 軸上的畫素數。

left

指定要滾動視窗或元素的 X 軸上的畫素數。

behavior

確定滾動是即時發生的還是平滑動畫的。此選項是一個字串,必須是以下值之一

  • smooth:滾動應該平滑動畫。
  • instant:滾動應該即時發生,一次性跳轉。
  • auto:滾動行為由 scroll-behavior 的計算值決定。

返回值

無(undefined)。

示例

js
// Put the 1000th vertical pixel at the top of the element
element.scroll(0, 1000);

使用 options

js
element.scroll({
  top: 100,
  left: 100,
  behavior: "smooth",
});

規範

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

瀏覽器相容性