此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
Window:scrollTo() 方法
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
Window.scrollTo() 会滚动到文档中的一组特定坐标。
In this article
语法
js
scrollTo(x-coord, y-coord)scrollTo(options)参数
x-coord是你希望显示在左上角的文档水平轴像素。y-coord是你希望显示在左上角的文档垂直轴像素。
——或者——
options包含以下参数的字典:
top指定沿 Y 轴滚动窗口或元素的像素数量。
left指定沿 X 轴滚动窗口或元素的像素数量。
behavior确定滚动是即时完成还是以平滑动画进行。该选项是一个字符串,必须取以下值之一:
smooth:滚动应该平滑地进行动画展示instant:滚动应在一次跳转中即时完成auto:滚动行为由scroll-behavior的计算值来决定
返回值
无(undefined)。
示例
js
window.scrollTo(0, 1000);使用options:
js
window.scrollTo({ top: 100, left: 100, behavior: "smooth",});备注
Window.scroll() 实际上与此方法相同。有关相对滚动,请参阅Window.scrollBy()、Window.scrollByLines() 和Window.scrollByPages()。
有关滚动元素,请参阅Element.scrollTop 和Element.scrollLeft。
规范
| Specification |
|---|
| CSSOM View Module> # dom-window-scrollto> |