javascript body.scrollTop vs documentElement.scrollTop vs window.pageYOffset vs window.scrollY
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19618545/
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
body.scrollTop vs documentElement.scrollTop vs window.pageYOffset vs window.scrollY
提问by Himanshu P
When trying to find out how much a web page has been scrolled from the top, which of these should one use:
当试图找出一个网页从顶部滚动了多少时,应该使用以下哪一个:
document.body.scrollTop
,
document.body.scrollTop
,
document.documentElement.scrollTop
,
document.documentElement.scrollTop
,
window.pageYOffset
,
window.pageYOffset
,
window.scrollY
window.scrollY
Which one(s) would I choose in these 2 separate scenarios:
在这 2 个不同的场景中,我会选择哪一个:
a) If I wanted maximum compatibility (across the main browsers used currently)?
a) 如果我想要最大的兼容性(跨当前使用的主要浏览器)?
b) If I wanted code that was most standards compliant/future-proof/strict-mode-compatible (but didn't care about supporting old/non-standard browsers)?
b) 如果我想要大多数标准兼容/面向未来/严格模式兼容的代码(但不关心支持旧的/非标准浏览器)?
回答by Prinzhorn
I'm using three of them in the skrollr source
我在 skrollr 源中使用了其中的三个
return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
a) So far it's working across all browsers (nobody complaint in the past year).
a) 到目前为止,它适用于所有浏览器(过去一年没有人抱怨)。
b) Since it will use the first one that is defined, I guess it's pretty future proof and stable.
b)由于它将使用定义的第一个,我想它是未来证明和稳定的。
If you're fancy you could do this as well
如果你喜欢你也可以这样做
Math.max(window.pageYOffset, document.documentElement.scrollTop, document.body.scrollTop)
回答by jasonklein
Given that skrollr does not use window.scrollY
, this may have been obvious, but as further answer to the original question: window.pageYOffset
is an alias for window.scrollY
. See Window.scrollY.
鉴于 skrollr 不使用window.scrollY
,这可能是显而易见的,但作为对原始问题的进一步回答:window.pageYOffset
is an alias for window.scrollY
. 请参阅Window.scrollY。
回答by Tom
To Prinzhorn's answear:
对Prinzhorn的回答:
Since body
and documentElement
is undefined
in Chrome/Firefox, better use:
由于body
和documentElement
是undefined
在Chrome / Firefox中,更好地利用:
return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
Tested myself.
本人测试过。
回答by yaya
Chrome uses documentElement.scrollTop
, firefox uses body.scrollTop
Chrome 使用documentElement.scrollTop
,firefox 使用body.scrollTop