下滑加载更多js_JS实现滚动条触底加载更多

原理

1.通过监听滚动区域DOM的scroll事件, 计算出触底

// 滚动可视区域高度 + 当前滚动位置 === 整个滚动高度

scrollDom.clientHeight + scrollDom.scrollTop === scrollDom.scrollHeight

2.触底后触发列表添加, 列表添加使用createDocumentFragment, 将多次插入的DOM先存入内存, 最后一次填充进去, 提高性能, 也方便后面的MutationObserver监听

3.使用MutationObserver监听列表的DOM添加, 添加完毕后, 隐藏加载中提示

示例

参考资料

代码

Document

.hide {

display: none;

}

.scroll {

height: 200px;

width: 300px;

overflow-y: auto;

border: 1px solid #ddd;

}

.loading {

text-align: center;

}

ul {

margin: 0;

padding: 0;

}

li {

padding: 10px;

margin: 10px;

text-align: center;

background: #FFF6F6;

list-style-type: none;

}

  • 000000
  • 000000
  • 000000
  • 000000
  • 000000
加载中...

let index = 0 // 列表个数

const listDom = document.getElementById('js-list')

const loadingDom = document.getElementById('js-loading')

/**

* 使用MutationObserver监听列表的 DOM 改变

*/

const config = {

attributes: true,

childList: true,

subtree: true

}

const callback = function(mutationsList, observer) {

for (let mutation of mutationsList) {

if (mutation.type === 'childList') {

if (index === 5) {

loadingDom.innerText = '加载完毕'

} else {

loadingDom.classList.add('hide')

}

}

}

}

const observer = new MutationObserver(callback)

observer.observe(listDom, config)

/**

* clientHeight 滚动可视区域高度

* scrollTop 当前滚动位置

* scrollHeight 整个滚动高度

*/

const scrollDom = document.getElementById('js-scroll')

scrollDom.onscroll = () => {

if (scrollDom.clientHeight + parseInt(scrollDom.scrollTop) === scrollDom.scrollHeight) {

if (loadingDom.classList.contains('hide') && index <= 5) {

loadingDom.classList.remove('hide')

addList()

}

if (index >= 5) {

observer.disconnect() // 加载完毕停止监听列表 DOM 变化

}

}

}

/**

* 添加列表

*/

function addList () {

const fragment = document.createDocumentFragment()

setTimeout(() => {

++index

for (let i = 0; i < 5; i++) {

const li = document.createElement('li')

li.innerText = new Array(6).fill(index).join('')

fragment.appendChild(li)

}

listDom.appendChild(fragment)

} , 1000)

}

总结

以上所述是小编给大家介绍的JS实现滚动条触底加载更多,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值