上拉loading加载原理

上拉加载原理
1、实现思路
滚定区域是给固定高度, 设置overflow-y:auto来实现
触发条件:可视高度 + 滚动高度 >= 实际高度
可视高度:通过dom的offsetHeight获取, 表示区域固定的高度; 但是更加推荐使用getBoundingClientRect()来获取高度, 因为使用前者会引起浏览器回流, 造成一些性能问题
滚动高度:滚动事件中通过e.target.scrollTop获取, 表示滚动条距离顶部的px
实际高度:通过dom的scrollHeight获取, 表示区域内所有内容的高度(包括滚定距离), 也就是实际的高度
2、基础实现
onScroll(e) {
let scrollTop = e.target.scrollTop
let scrollHeight = e.target.scrollHeight
let offsetHeight = Math.ceil(e.target.getBoundingClientRect().height)
let currentHeight = scrollTop + offsetHeight
if(currentHeight >= scrollHeight) {
console.log(‘触底’)
}
}
3、优化:添加触底距离
希望离底部还有一定距离就触发事件, 而不是等到完全触底, 和小程序的onReachBottom差不多
声明一个离底部的距离变量reachBottomDistance
此时的触发条件为:可视高度 + 滚动距离 + reachBottomDistance >= 实际高度
export default {
data() {
return {
reachBottomDistance: 100
}
},
methods: {
onScroll(e) {
let scrollTop = e.target.scrollTop
let scrollHeight = e.target.scrollHeight
let offsetHeight = Math.ceil(e.target.getBoundingClientRect().height)
let currentHeight = scrollTop + offsetHeight + this.reachBottomDistance
if(currentHeight >= scrollHeight) {
console.log(‘触底’)
}
}
}
}
4、优化:进入后只触发一次
在距离底部100px时成功触发事件, 但是由于100px以下的区域是符合条件的, 会导致一直触发, 所以需要做一些处理, 让其进入后只触发一次
export default {
data() {
return {
isReachBottom: false,
reachBottomDistance: 100
}
},
methods: {
onScroll(e) {
let scrollTop = e.target.scrollTop
let scrollHeight = e.target.scrollHeight
let offsetHeight = Math.ceil(e.target.getBoundingClientRect().height)
let currentHeight = scrollTop + offsetHeight + this.reachBottomDistance
if(currentHeight < scrollHeight && this.isReachBottom){
this.isReachBottom = false
}
if(this.isReachBottom) return
if(currentHeight >= scrollHeight) {
this.isReachBottom = true
console.log(‘触底’)
}
}
}
}
5、优化:实时获取可变, 不可变缓存
实时去获取位置信息会损耗性能, 应该将不变的缓存起来, 只获取实时可变的部分
export default {
data() {
return {
isReachBottom: false,
reachBottomDistance: 100,
scrollHeight: 0,
offsetHeight: 0
}
},
mounted() {
// -> 页面加载完成后将高度缓存起来
let dom = document.querySelector(’.list’)
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
if(currentHeight < this.scrollHeight && this.isReachBottom){
this.isReachBottom = false
}
if(this.isReachBottom) return
if(currentHeight >= this.scrollHeight) {
this.isReachBottom = true
console.log(‘触底’)
}
}
}
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JackieChan_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值