body.scrollTop与documentElement.scrollTop与window.pageYOffset与window.scrollY [英] body.scrollTop vs documentElement.scrollTop vs window.pageYOffset vs window.scrollY

查看:228
本文介绍了body.scrollTop与documentElement.scrollTop与window.pageYOffset与window.scrollY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当试图找出从顶部滚动了多少网页时,应使用以下哪一种:

When trying to find out how much a web page has been scrolled from the top, which of these should one use:

文档。 body.scrollTop

document.documentElement.scrollTop

window.pageYOffset

window。 scrollY

在以下两种不同的情况下,我会选择哪个?

Which one(s) would I choose in these 2 separate scenarios:

a)如果我想要最大的兼容性(跨当前使用的主要浏览器)?

a) If I wanted maximum compatibility (across the main browsers used currently)?

b)如果我想要的代码最符合标准/面向未来/严格-mode-compatible(但不关心支持旧/非标准浏览器)吗?

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)?

推荐答案

我正在使用三个其中的其中一个在skrollr源中

I'm using three of them in the skrollr source

return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

https://github.com/Prinzhorn/skrollr/blob/b98d40820b9864be275e81af382045d72cc5a08a/src/skrollr.js#L627

a)到目前为止,它可以在所有浏览器上正常工作(在过去的一年中没有人投诉)。

a) So far it's working across all browsers (nobody complaint in the past year).

b)因为它将使用第一个

b) Since it will use the first one that is defined, I guess it's pretty future proof and stable.

如果您愿意,也可以这样做

If you're fancy you could do this as well

Math.max(window.pageYOffset, document.documentElement.scrollTop, document.body.scrollTop)

这篇关于body.scrollTop与documentElement.scrollTop与window.pageYOffset与window.scrollY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆