Window: scroll() 方法

Baseline 已廣泛支援

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

Window.scroll() 方法會將視窗滾動到文件中的特定位置。

語法

js
scroll(xCoord, yCoord)
scroll(options)

引數

xCoord

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

yCoord

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

options

包含以下屬性的物件:

top

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

left

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

behavior

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

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

返回值

無(undefined)。

示例

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

使用 options

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

注意

Window.scrollTo() 方法與此方法基本相同。有關相對滾動,請參閱 Window.scrollBy()Window.scrollByLines()Window.scrollByPages()

有關滾動元素,請參閱 Element.scrollTopElement.scrollLeft

規範

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

瀏覽器相容性

另見