JS 原生实现触底加载

  1. 创建一个容器来存储列表项。

  2. 监听滚动事件,当滚动接近底部时触发加载更多操作。

  3. 加载更多数据后,将新数据附加到容器中。

以下是一个简单的示例:

<!DOCTYPE html>
<html>

<head>
  <style>
    #scroll-container {
      height: 200px;
      overflow: auto;
    }

    .item {
      height: 50px;
      background: #eee;
      margin-bottom: 10px;
    }
  </style>
</head>

<body>
  <div id="scroll-container">
    <div class="item">Item 1</div>
    <div class="item">Item 2</div>
    <div class="item">Item 3</div>
    <div class="item">Item 4</div>
    <div class="item">Item 5</div>
    <!-- Add more items here -->
  </div>

  <script>
    const scrollContainer = document.getElementById("scroll-container");
    scrollContainer.addEventListener("scroll", () => {
      // scrollContainer.scrollTop : 当前可视化到容器最顶部的距离
      // scrollContainer.clientHeight : 当前可视化的高度
      // scrollContainer.scrollHeight : 当前容器的滚动高度
      if (
        scrollContainer.scrollTop + scrollContainer.clientHeight >=
        scrollContainer.scrollHeight
      ) {
        // Load more data and append it to the container
        for (let i = 0; i < 5; i++) {
          const newItem = document.createElement("div");
          newItem.className = "item";
          newItem.textContent = `Item ${scrollContainer.childElementCount + 1}`;
          scrollContainer.appendChild(newItem);
        }
      }
    });
  </script>
</body>

</html>

触底加载

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值