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

浏览器兼容性

另见