上拉加载更多(Pull to Load More) 是一种常见的移动端交互设计,用户在浏览内容时,当滚动到页面底部时,可以通过向上拉或点击加载更多按钮来加载额外的内容。
以下是一个简单的无限滚动实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Infinite Scroll Example</title>
<style>
.item {
height: 200px;
border: 1px solid #ccc;
margin: 10px;
}
</style>
</head>
<body>
<div id="content">
<!-- 初始内容 -->
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<!-- 更多内容将在这里动态添加 -->
</div>
<script>
let loading = false;
const content = document.getElementById('content');
const itemHeight = 200; // 每个项目的高度
const visibleItems = Math.ceil(window.innerHeight / itemHeight); // 可见项目数
let allItemsLoaded = false;
function loadMoreItems() {
if (loading || allItemsLoaded) return;
loading = true;
// 模拟异步加载数据
setTimeout(() => {
for (let i = 0; i < visibleItems; i++) {
const newItem = document.createElement('div');
newItem.className = 'item';
newItem.textContent = `Item ${content.children.length + 1}`;
content.appendChild(newItem);
}
loading = false;
}, 1000);
}
window.addEventListener('scroll', () => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - itemHeight) {
loadMoreItems();
}
});
// 初始加载一些数据
loadMoreItems();
</script>
</body>
</html>
loading
),确保在数据加载完成前不再触发新的加载请求。通过上述方法,可以有效实现并优化手机端的上拉加载更多功能,提升用户体验和应用性能。
领取专属 10元无门槛券
手把手带您无忧上云