滚动条距离底部200px时,开启ajax请求
1. 出现在body的滚动条
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="min-height: 5000px;">
<div style="margin-top:1000px">
2222
</div>
<script>
window.onscroll = function() {
const isflag = isScrollToPageBottom()
console.log(isflag)
}
function isScrollToPageBottom() {
// 文档高度
const offsetHeight = document.documentElement.offsetHeight
// 浏览器窗口高度
const innerHeight = window.innerHeight
// 页面滚动条的垂直距离
const scrollY = window.scrollY
console.log(offsetHeight, innerHeight, scrollY)
return offsetHeight - scrollY - innerHeight < 200
}
</script>
</body>
</html>
2. 出现在具体位置时的滚动条
<template>
<div ref="content"></div>
</template>
data() {
return {
searchCondition: {
pageNum: 1,
pageSize: 23,
total: 0,
pages: 0,
},
}
},
created() {
// 初始化数据
this.initData()
window.addEventListener('scroll', this.handleScroll, true)
},
destroyed() {
window.removeEventListener('scroll', this.handleScroll, false)
},
methods: {
initData() {
getSourceList({ ...this.searchCondition })
.then((data) => {
const sourceLists = (data && data.data.resourceDataList) || []
this.searchCondition.total = data.data.total
this.searchCondition.pages = data.data.pages
// 如果是:第1页,直接赋值,不是第1页,就concat到数组中
this.sourceLists = this.searchCondition.pageNum === 1 ? sourceLists : this.sourceLists.concat(sourceLists)
})
},
// 滚动条的位置在body时,获取到的相关数据(跟当前的需求不符合)
isScrollToPageBottom() {
// 文档高度
const offsetHeight = document.documentElement.offsetHeight
// 浏览器窗口高度
const innerHeight = window.innerHeight
// 页面滚动条的垂直距离
const scrollY = window.scrollY
return offsetHeight - scrollY - innerHeight < 100
},
handleScroll() {
const { pageSize, pageNum, total, pages } = this.searchCondition
const content = this.$refs.content
if (content) {
// 当前容器 文档高度
const offsetHeight = content.offsetHeight
// 浏览器窗口高度
const innerHeight = window.innerHeight
// 当前容器 滚动条的垂直距离
//(这里注意下面的:document.querySelector是获取滚动条的具体位置,一定要准确找到滚动条的位置,否则获取到的数据为0)
const scrollY = document.querySelector('.main-scrollbar .el-scrollbar__wrap').scrollTop
// 当滚动条距离地步100px时,开启ajax的请求
if (offsetHeight - scrollY - innerHeight < 100) {
if (pageNum !== pages) {
this.searchCondition.pageNum += 1
this.initData()
}
}
}
},
}