document.documentElement.scrollTop return value differs in Chrome

后端 未结 5 1266
既然无缘
既然无缘 2020-12-03 02:52

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 return

5条回答
  •  鱼传尺愫
    2020-12-03 03:25

    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 element whilst Firefox defines it on the 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)

提交回复
热议问题