Window.scrollY
Baseline Widely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2020.
* Some parts of this feature may have varying levels of support.
概述
返回文档在垂直方向已滚动的像素值。
语法
var y = window.scrollY;
y
是文档从顶部开始滚动过的像素值。
示例
js
// 保证刚好滚动到第二页
if (window.scrollY) {
window.scroll(0, 0); // 重置滚动位置为文档的左上角
}
window.scrollByPages(1);
备注
如果正在使用相对滚动函数,如 window.scrollBy
、window.scrollByLines
或 window.scrollByPages
,则需要使用该属性来检测文档是否已被滚动了某段距离。
pageYOffset
属性是 scrollY
属性的别名:
window.pageYOffset == window.scrollY; // 总是返回 true
为了跨浏览器兼容,请使用 window.pageYOffset
代替 window.scrollY
。另外,旧版本 IE(<9)两个属性都不支持,必须使用其他的非标准属性。完整的兼容性代码如下:
js
var supportPageOffset = window.pageXOffset !== undefined;
var isCSS1Compat = (document.compatMode || "") === "CSS1Compat";
var x = supportPageOffset
? window.pageXOffset
: isCSS1Compat
? document.documentElement.scrollLeft
: document.body.scrollLeft;
var y = supportPageOffset
? window.pageYOffset
: isCSS1Compat
? document.documentElement.scrollTop
: document.body.scrollTop;
规范
Specification |
---|
CSSOM View Module # dom-window-scrolly |
Browser compatibility
Report problems with this compatibility data on GitHubdesktop | mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
scrollY | ||||||||||||
Subpixel precision |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
- No support
- No support
- Uses a non-standard name.
- Has more compatibility info.
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.