IT柠檬

document scrollingElement scroll

2018-10-26  本文已影响90人  Dannn_Y

最近在检测网页异常情况,添加了监测的系统,跑了一段时间,发现报错最多的就是Cannot read 'scrollTop' of undefined设备大多数基本上都是Android手机

检查了一下代码发现,有用到scrollTop的时候只有在滚动加载的时,获取页面滚动的高度,代码如下

document.scrollingElement.scrollTop

只有这个地方用到了scrollTop,难道是scrollingElement的问题,于是查找了一些资料,如下

引用MDN文档解释Document.scrollingElement的作用

scrollingElement(Document的只读属性)返回滚动文档的Element对象的引用。在标准模式下,这是文档的根元素,document.documentElement
当在怪异模式下,scrollingElement属性返回HTML body元素(若不存在返回null)

也就是说scrollingElement在标准模式下可以被当做文档的根元素,不过现在大部分网页都是标准模式下。那接下来就看看兼容性问题。

scrollingElement 兼容性

PC端兼容性

PC

手机端兼容性

手机端

看这两张图就能看出来,兼容性并不是很好,Android并不支持此对象,所以在Android手机上会报错。
那除了这元素,还有什么办法获取页面内容的滚动高度呢?

看过这个jsfiddle发现还可以使用document.bodydocument.documentElement的方式,我分别将这个jsfiddle在Chrome浏览器下运行,和在Safari下运行得到的结果却不同,结果如下:

Chrome执行结果

document.documentElement.scrollTop: 77 
document.body.scrollTop: 0 
document.scrollingElement.scrollTop: 77

Safari执行结果

document.documentElement.scrollTop: 0
document.body.scrollTop: 77
document.scrollingElement.scrollTop: 77

对比结果就发现,在Chrome中document.body.scrollTop获取到的值为0,而在Safari中是有值的,但document.documentElement.scrollTop却没有值得到0

兼容性解答方法获取scrollTop

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

看了好多资料都说document.documentElement.scrollTop已经弃用,但是Safari还是可以用的,难道兼容了。更安全的写法就是上面都兼容下

或者把scrollingElement也加上

function pageScrollTop {
  if (document.scrollingElement) {
    return document.scrollingElement.scrollTop
  }

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

参考链接:

https://stackoverflow.com/questions/28633221/document-body-scrolltop-firefox-returns-0-only-js

上一篇下一篇

猜你喜欢

热点阅读