document scrollingElement scrollTop 的問(wèn)題

最近在檢測(cè)網(wǎng)頁(yè)異常情況,添加了監(jiān)測(cè)的系統(tǒng),跑了一段時(shí)間,發(fā)現(xiàn)報(bào)錯(cuò)最多的就是Cannot read 'scrollTop' of undefined設(shè)備大多數(shù)基本上都是Android手機(jī)

檢查了一下代碼發(fā)現(xiàn),有用到scrollTop的時(shí)候只有在滾動(dòng)加載的時(shí),獲取頁(yè)面滾動(dòng)的高度,代碼如下

document.scrollingElement.scrollTop

只有這個(gè)地方用到了scrollTop,難道是scrollingElement的問(wèn)題,于是查找了一些資料,如下

引用MDN文檔解釋Document.scrollingElement的作用

scrollingElement(Document的只讀屬性)返回滾動(dòng)文檔的Element對(duì)象的引用。在標(biāo)準(zhǔn)模式下,這是文檔的根元素,document.documentElement
當(dāng)在怪異模式下,scrollingElement屬性返回HTML body元素(若不存在返回null)

也就是說(shuō)scrollingElement在標(biāo)準(zhǔn)模式下可以被當(dāng)做文檔的根元素,不過(guò)現(xiàn)在大部分網(wǎng)頁(yè)都是標(biāo)準(zhǔn)模式下。那接下來(lái)就看看兼容性問(wèn)題。

scrollingElement 兼容性

PC端兼容性

PC

手機(jī)端兼容性

手機(jī)端

看這兩張圖就能看出來(lái),兼容性并不是很好,Android并不支持此對(duì)象,所以在Android手機(jī)上會(huì)報(bào)錯(cuò)。
那除了這元素,還有什么辦法獲取頁(yè)面內(nèi)容的滾動(dòng)高度呢?

看過(guò)這個(gè)jsfiddle發(fā)現(xiàn)還可以使用document.bodydocument.documentElement的方式,我分別將這個(gè)jsfiddle在Chrome瀏覽器下運(yùn)行,和在Safari下運(yùn)行得到的結(jié)果卻不同,結(jié)果如下:

Chrome執(zhí)行結(jié)果

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

Safari執(zhí)行結(jié)果

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

對(duì)比結(jié)果就發(fā)現(xiàn),在Chrome中document.body.scrollTop獲取到的值為0,而在Safari中是有值的,但document.documentElement.scrollTop卻沒(méi)有值得到0

兼容性解答方法獲取scrollTop

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

看了好多資料都說(shuō)document.documentElement.scrollTop已經(jīng)棄用,但是Safari還是可以用的,難道兼容了。更安全的寫(xiě)法就是上面都兼容下

或者把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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容