-
创建一个容器来存储列表项。
-
监听滚动事件,当滚动接近底部时触发加载更多操作。
-
加载更多数据后,将新数据附加到容器中。
以下是一个简单的示例:
<!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 containerfor (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>
触底加载