metroluffy / blog

用于记录平时开发中所遇到问题的解决方法、笔记等
9 stars 1 forks source link

正确获取页面ScrollTop的值 #14

Open metroluffy opened 6 years ago

metroluffy commented 6 years ago

在开发微信H5时遇到了其内置浏览器document.documentElement.scrollTop值为0的问题,下面函数可以正确获取页面ScrollTop的值,

  getDPSize () {
    let scrollTop
    let scrollHeight
    let clientHeight
    if (typeof document.compatMode !== 'undefined' && document.compatMode !== 'BackCompat') {
      scrollTop = document.documentElement.scrollTop
      scrollHeight = document.documentElement.scrollHeight
      clientHeight = document.documentElement.clientHeight
    } else if (typeof document.body !== 'undefined') {
      scrollTop = document.body.scrollTop
      scrollHeight = document.body.scrollHeight
      clientHeight = document.body.clientHeight
    }
    if (typeof window.pageYOffset !== 'undefined' && scrollTop === 0) { // pageYOffset指的是滚动条顶部到网页顶部的距离
      scrollTop = window.pageYOffset
    }
    return {
      scrollTop,
      scrollHeight,
      clientHeight
    }
}

[参考资料] scrollTop为0的问题