Chrome中的document.documentElement.scrollTop返回值有所不同 [英] document.documentElement.scrollTop return value differs in Chrome
问题描述
我试图根据' document.documentElement.scrollTop
'的值处理一些代码。它在FF和IE中返回' 348
',但在Chrome中返回' 0
'。我需要做任何事情来克服这个问题吗?
FF:
>>> document.documentElement.scrollTop
342
Chrome:
document.documentElement.scrollTop
0
获取滚动条的基于标准的方法是 window.scrollY
。这受Chrome,Firefox,Opera,Safari和IE Edge或更高版本的支持。如果您只支持这些浏览器,则应该使用此属性。
IE> = 9支持类似的属性 window.pageYOffset
,为了兼容性的缘故,它在近期的浏览器中返回与 window.scrollY
相同的内容,尽管在某些时候可能会被弃用。
使用 document.documentElement.scrollTop
或 document.body.scrollTop
是不需要在任何一个上定义滚动。 Chrome和Safari在< body>
元素上定义了滚动,而Firefox则在< html>
元素上定义了它们例如,由 document.documentElement
返回。这不是标准化的,并且可能在未来版本的浏览器中发生变化。但是,如果 scrollY
或 pageYOffset
不存在,这是获取滚动的唯一方法。
TL; DR:
window.scrollY || window.pageYOffset || document.body.scrollTop +(document.documentElement&& document.documentElement.scrollTop || 0)
I am trying to process some code based on the 'document.documentElement.scrollTop
' value. It returns '348
' in FF and IE but in Chrome it returns '0
'. Do i need to do anything to overcome this issue?
FF:
>>> document.documentElement.scrollTop
342
Chrome:
document.documentElement.scrollTop
0
The standards-based way of getting the scroll is window.scrollY
. This is supported by Chrome, Firefox, Opera, Safari and IE Edge or later. If you only support these browsers, you should go with this property.
IE >= 9 supports a similar property window.pageYOffset
, which for the sake of compatibility returns the same as window.scrollY
in recent browsers, though it may perhaps be deprecated at some point.
The problem with using document.documentElement.scrollTop
or document.body.scrollTop
is that the scroll needn't be defined on either of these. Chrome and Safari define their scroll on the <body>
element whilst Firefox defines it on the <html>
element returned by document.documentElement
, for example. This is not standardized, and could potentially change in future versions of the browsers. However, if the scrollY
or pageYOffset
are not present, this is the only way to get the scroll.
TL;DR:
window.scrollY || window.pageYOffset || document.body.scrollTop + (document.documentElement && document.documentElement.scrollTop || 0)
这篇关于Chrome中的document.documentElement.scrollTop返回值有所不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!