JS滚动条触底加载更多

原理

  1. 通过监听滚动区域DOM的scroll事件, 计算出触底
// 滚动可视区域高度 + 当前滚动位置 === 整个滚动高度
scrollDom.clientHeight + scrollDom.scrollTop === scrollDom.scrollHeight
  1. 触底后触发列表添加, 列表添加使用createDocumentFragment, 将多次插入的DOM先存入内存, 最后一次填充进去, 提高性能, 也方便后面的MutationObserver监听
  2. 使用MutationObserver监听列表的DOM添加, 添加完毕后, 隐藏加载中提示

示例

https://codepen.io/klren0312/full/dybgayL

JS滚动条触底加载更多_第1张图片
2.gif

参考资料

https://developer.mozilla.org/zh-CN/docs/Web/API/Element/clientHeight
https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollHeight
https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollTop
https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalEventHandlers/onscroll
https://developer.mozilla.org/zh-CN/docs/Web/API/Document/createDocumentFragment
https://developer.mozilla.org/zh-CN/docs/Web/API/MutationObserver

代码




  
  
  
  Document
  


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

你可能感兴趣的:(JS滚动条触底加载更多)