来,手写一个van-list

使用原生javascript实现一个加载更多组件

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title></title>
</head>

<body>
  <div id="pub_header"></div>
  <div id="app"></div>
  <div id="loadingEl">加载中...</div>
  <div id="placeHolder"></div>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    #loadingEl {
      text-align: center;
    }
  </style>
  <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
  <script>
    let clientHeight = document.documentElement.clientHeight;
    console.log('可视高度=', clientHeight);
    let placeHolder = document.getElementById("placeHolder");
    let loadingEl = document.getElementById("loadingEl");

    let immediate = true; // 是否立即执行
    let loading = false; // 是否加载
    let finished = false; // 是否已经加载完
    let offset = 100; // 距离底部偏移量触发加载

    // 初始化页面函数
    function init() {
      if (immediate) {
        loadNextPage().then(res => {
          if (res.status === 200) {
            if (document.body.offsetHeight < clientHeight) {
              init()
            }
          }
        })
      }
    }

    // 加载更多
    function loadNextPage() {
      if (!loading) loading = true;
      loadingEl.style.display = 'block';
      return new Promise((resolve, reject) => {
        setTimeout(function () {
          let appEl = document.getElementById("app");
          for (let i = 0; i < 10; i++) {
            let el = document.createElement("div");
            el.innerHTML = `${Math.random()}`;
            appEl.appendChild(el);
          }
          loading = false;
          loadingEl.style.display = 'none';
          resolve({ status: 200 });
        }, 2000)
      })
    }

    // 滚动监听
    window.addEventListener("scroll", function (e) {
      // 可以加个节流优化性能
      if (finished) return;
      const rect = placeHolder.getBoundingClientRect();
      if (rect.top <= (clientHeight + offset) && !loading) {
        console.log("触底了");
        loading = true;
        loadNextPage();
      }
    });

    init();
  </script>
</body>

</html>

复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享