document.documentElement.scrollTop返回值在Chrome中有所不同

我试图基于’ document.documentElement.scrollTop ‘值处理一些代码。 它在FF和IE中返回’ 348 ‘,但在Chrome中它返回’ 0 ‘。 我是否需要做任何事情来克服这个问题?

FF:

 >>> document.documentElement.scrollTop 342 

铬:

 document.documentElement.scrollTop 0 

获取滚动的基于标准的方法是window.scrollY 。 Chrome,Firefox,Opera,Safari和IE Edge或更高版本均支持此function。 如果您只支持这些浏览器,则应使用此属性。

IE> = 9支持类似的属性window.pageYOffset ,为了兼容性,它在最近的浏览器中返回与window.scrollY相同,尽管它可能在某些时候被弃用。

使用document.documentElement.scrollTopdocument.body.scrollTop的问题是无需在其中任何一个上定义滚动。 Chrome和Safari在元素上定义它们的滚动,而Firefox在document.documentElement返回的元素上定义它,例如。 这不是标准化的,并且可能在未来版本的浏览器中发生变化。 但是,如果不存在scrollYpageYOffset ,则这是获取滚动的唯一方法。

TL; DR:

window.scrollY || window.pageYOffset || document.body.scrollTop + (document.documentElement && document.documentElement.scrollTop || 0)

试试这个

 window.pageYOffset || document.documentElement.scrollTop 

您可以使用以下代码来修复该错误!

 let scrollHeight = document.body.scrollTop || document.documentElement.scrollTop; console.log(`scrollHeight = ${scrollHeight}`); /* this comment just using for testing the scroll height! but in this iframe it deon't work at all! So, you can try it out using Chrome console! */ 

尽可能使用window.scrollY ,它被设计为跨浏览器保持一致。 如果你需要支持IE,那么我建议以下只使用window.scrollY如果它可用:

 typeof window.scrollY === "undefined" ? window.pageYOffset : window.scrollY 

如果window.scrollY || window.pageYOffset返回0,则将其评估为false,因此执行window.scrollY || window.pageYOffset window.scrollY || window.pageYOffset技术上会在window.scrollY为0时检查window.pageYOffset ,如果window.pageYOffset也不等于0,这显然是不理想的。

另请注意,如果您需要经常获取滚动值(每帧/每个滚动),通常情况下,您可能需要检查是否事先定义了window.scrollY 。 我喜欢使用我编写的这个小帮助函数,以及使用requestAnimationFrame – 它应该在IE10及以上版本中工作。

 function registerScrollHandler (callback) { "use strict" var useLegacyScroll = typeof window.scrollY === "undefined", lastX = useLegacyScroll ? window.pageXOffset : window.scrollX, lastY = useLegacyScroll ? window.pageYOffset : window.scrollY function scrollHandler () { // get the values using legacy scroll if we need to var thisX = useLegacyScroll ? window.pageXOffset : window.scrollX, thisY = useLegacyScroll ? window.pageYOffset : window.scrollY // if either the X or Y scroll position changed if (thisX !== lastX || thisY !== lastY) { callback(thisX, thisY) // save the new position lastX = thisX lastY = thisY } // check again on the next frame window.requestAnimationFrame(scrollHandler) } scrollHandler() } 

使用这样的function:

 registerScrollHandler(function (x, y) { /* your code here :) */ console.log("Scrolled the page", x, y) })