移动端滚动加载数据判断是否滚动到页面底部

获取scrollTop,scrollTop是可见窗口顶端与body对象最顶端的距离,即滚动鼠标或手指滑动页面时,隐藏的页面高度(滚动的距离)。

documentElement对应的是html标签,body对应的body标签,在标准w3c下,document.body.scrollTop恒为0,需要用documnet.documentElement.scrollTop来代替,两者只有一个生效,始终有一个为0。

  function getScrollTop () {
    // 考虑到浏览器版本兼容性问题,解析方式可能会不一样
  return document.documentElement.scrollTop || document.body.scrollTop
}

获取视口高度(网页可见区域高)

function getWinHeight () {
  // 浏览器可见内容高度 || 浏览器所有内容高度(考虑到浏览器版本兼容性问题,解析方式可能会不一样)
  return document.documentElement.clientHeight || document.body.clientHeight
}

获取文档总高度

function getScrollHeight() {
  let bodyScrollHeight = 0
  let documentScrollHeight = 0
  if (document.body) {
    bodyScrollHeight = document.body.scrollHeight
  }
  if (document.documentElement) {
    documentScrollHeight = document.documentElement.scrollHeight
  }
  // 当页面内容超出浏览器可视窗口大小时,Html的高度包含body高度+margin+padding+border所以html高度可能会大于body高度
  return (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight
}

是否滚动到底部

function isReachBottom () {
  const scrollTop = getScrollTop() // 获取滚动条的高度
  const winHeight = getWinHeight() // 一屏的高度
  const scrollHeight = getScrollHeight() // 获取文档总高度
  return scrollTop >= parseInt(scrollHeight) - winHeight
}

导出函数

export default isReachBottom

使用函数

// 判断是否到页面底部,如果到页面底部,判断是否还有数据,如果有数据就加载,如果没有,就解绑滚动事件
import isReachBottom from 'isReachBottom'

methods: {
  reachBottom() {
    if (isReachBottom()) {
      if (this.hasMore) {
        this.queryInfo()
      } else {
        window.onscroll = null
      }
    }
  }
}
watch: {
  // 判断是否是需要滑动加载数据的页面
  investShow() {
    // 如果是需要滑动加载数据的页面,就绑定reachBottomg事件
    window.addEventListener("scroll", this.reachBottom)
  } else {
    // 否则移除
    window.removeEventListener("scroll", this.reachBottom)
  }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值