JavaScript 中的垂直文档滚动位置,跨浏览器兼容至 IE 8

Sun*_*nil 0 javascript scroll-position

我想要 JavaScript 中文档元素的滚动位置,因为我无法使用 jQuery。

问题:获取文档垂直滚动位置的 JavaScript 代码是什么?我需要使其兼容 IE 8 和所有现代浏览器。

更新 1:我查看了与此重复的 2 个答案。第一个确实解决了我的问题,尽管它不关注跨浏览器解决方案,但第二个远远超出了我的需要。我需要文档的垂直滚动位置,而不是滚动到文档顶部。第二篇文章讨论了使用链接或逐步转到文档顶部,这没有解决我的问题。

更新 2:根据 minitech 提供的答案,我提出了以下函数来确定适用于所有现代浏览器以及 IE 8 之前的滚动位置。我对此进行了测试,它适用于 Chrome、FireFox、Opera、Edge 、IE 8、IE 9、IE 10 和 IE 11。

function getScrollY() {
        return  window.scrollY || window.pageYOffset || document.body.scrollTop;
}

function getScrollX() {
    return window.scrollX || window.pageXOffset || document.body.scrollLeft;
}
Run Code Online (Sandbox Code Playgroud)

Ry-*_*Ry- 5

使用来源:

\n\n
var scrollPosition = window.pageYOffset;\n
Run Code Online (Sandbox Code Playgroud)\n\n

兼容性注意事项:

\n\n
    \n
  • document.body.scrollTop在 Firefox 中\xe2\x80\x99 不起作用(始终为 0);document.documentElement.scrollTop如果你想使用 ascrollTop的话,它\xe2\x80\x99s 。相反,document.documentElement.scrollTop在 Chrome 中始终为 0(还有 Blink 和 WebKit)。

  • \n
  • window.scrollYIE 8 及更早版本中不存在\xe2\x80\x99。

  • \n
\n\n

因此,为了兼容旧版 IE,请使用:

\n\n
var scrollPosition =\n    \'pageYOffset\' in window ?\n        window.pageYOffset :\n        document.body.scrollTop;\n
Run Code Online (Sandbox Code Playgroud)\n