1.vue组件添加滚动事件:
<template>
<div class="body-container" @scroll="scrollEvent">
</div>
<template>
export default {
name: 'demo',
data () {
return {
msg: '',
}
},
methods: {
scrollEvent(e){
//当前盒子的滚动高度+当前盒子绝对高度>当前盒子可滚动高度-100px时,加载更多
if(e.srcElement.scrollTop+e.srcElement.offsetHeight>e.srcElement.scrollHeight-100){
console.log()
}
},
}
- 计算滚动盒子高度
移动端中滚动框的高度受设备的影响,由于移动端中使用rem的缘故,因此高度是不定的,所以计算高度是不可少的。
一般使用
document.getElementById(‘div’).offsetHeight;
document.body.offsetHeight
获取元素的高度,用这种方法将设备高度减去不滚动的区域高度,就是滚动区域的高度了。
3.添加滚动条事件
export default {
name: 'demo',
data () {
return {
msg: '',
}
},
methods: {
handleScroll(e){
// 滚动条到顶部的位置
const scrollTop = e.srcElement.scrollTop
// 滚动条内容的总高度
const scrollHeight = e.srcElement.scrollHeight
// 可视窗口高度
const offsetHeight = e.srcElement.offsetHeight
console.log(scrollTop+" "+scrollHeight+" "+offsetHeight);
// 滚动的像素+容器的高度>可滚动的总高度
if (scrollTop + offsetHeight - scrollHeight >= -100) {
this.currentPage++;
if(this.currentPage < this.total/this.pageSize){
this.initial1()
}
}
}
},
mounted() {
window.addEventListener('scroll',this.handleScroll,true)
}