欢迎您光临自学哈网,只为分享网络知识教程,供大家学习参考!

「自学哈网」js实现滚动条触底后加载内容

作者 : 自学哈 本文共1565个字,预计阅读时间需要4分钟 2023-08-4 共58人阅读
也想出现在这里? 联系我们

原理

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

// 滚动可视区域高度 + 当前滚动位置 === 整个滚动高度
scrollDom.clientHeight + scrollDom.scrollTop === scrollDom.scrollHeight

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

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

 <div id="js-scroll" class="scroll">
    <ul id="js-list">
      <li>000000</li>
      <li>000000</li>
      <li>000000</li>
      <li>000000</li>
      <li>000000</li>
    </ul>
    <div class="loading hide" id="js-loading">加载中...</div>
  </div>
  <script>
    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)
    }

  </script>

 

本站声明:
本站所有资源来源于网络,分享目的仅供大家学习和交流!如若本站内容侵犯了原著者的合法权益,可联系邮箱976157886@qq.com进行删除。
自学哈专注于免费提供最新的分享知识、网络教程、网络技术的资源分享平台,好资源不私藏,大家一起分享!

自学哈网 » 「自学哈网」js实现滚动条触底后加载内容
也想出现在这里? 联系我们
© 2022 Theme by - 自学哈网 & WordPress Theme. All rights reserved 浙ICP备2022016594号