实现思路
之前写过一篇触底加载,经过一番苦学钻研,优化一下
样式方面:滚动区域是给固定高度,设置 overflow-y: auto
来实现。
接下来看看js方面的实现,其实也很简单,触发的条件是:可视高度
+ 滚动距离
>= 实际高度
。例子我会使用vue
来实现,和原生实现是一样的。
- 可视高度(offsetHeight):通过
dom
的 offsetHeight
获得,表示区域固定的高度。通过 getBoundingClientRect()
来获取高度,因为使用前者会引起浏览器回流,造成一些性能问题。
- 滚动高度(scrollTop):滚动事件中通过
e.target.scrollTop
获取,表示滚动条距离顶部的px
- 实际高度(scrollHeight):通过
dom
的 scrollHeight
获得,表示区域内所有内容的高度(包括滚动距离),也就是实际高度
export default {
data(){
return {
isReachBottom: false,
reachBottomDistance: 100
scrollHeight: 0,
offsetHeight: 0,
}
},
mounted(){
// 页面加载完成后 将高度存储起来
let dom = document.querySelector('.div')
this.scrollHeight = dom.scrollHeight
this.offsetHeight = Math.ceil(dom.getBoundingClientRect().height)
},
methods: {
onScroll(e) {
let scrollTop = e.target.scrollTop
let currentHeight = scrollTop + this.offsetHeight + this.reachBottomDistance//距离底部还有100px空余
if(currentHeight < this.scrollHeight && this.isReachBottom){
this.isReachBottom = false
}
if(this.isReachBottom){
return
}
if (currentHeight >= this.scrollHeight) {
this.isReachBottom = true
console.log('触底')
//执行加载数据操作
}
}
}
}