在 Javascript 中获取滚动位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31712287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:14:18  来源:igfitidea点击:

Get scroll position in Javascript

javascriptscrollcross-browser

提问by user5171262

I would like to retrieve the current scroll position in Javascript, after some research I found this: window.scrollYand window.scollTop.

我想在 Javascript 中检索当前的滚动位置,经过一些研究,我发现了这个:window.scrollYwindow.scollTop.

But the problem is that it does not work 100% on all browsers, is there something more reliable?

但问题是它不能在所有浏览器上 100% 工作,还有更可靠的东西吗?

回答by BigMac

The solution for JavaScript is:

JavaScript 的解决方案是:

var scrollPos = window.scrollY || window.scrollTop || document.getElementsByTagName("html")[0].scrollTop;

Or if you use jQuery (this is more reliable, due cross-browser support):

或者,如果您使用 jQuery(由于跨浏览器支持,这更可靠):

var scrollPos = $(window).scrollTop();

回答by callback

For cross-browser compatibility, use window.pageYOffset

为了跨浏览器兼容性,请使用 window.pageYOffset

https://developer.mozilla.org/en-US/docs/Web/API/Window/pageYOffset

https://developer.mozilla.org/en-US/docs/Web/API/Window/pageYOffset