获取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)
}
}