下滑加载更多(Infinite Scroll)是一种网页加载技术,用户在浏览页面时,当滚动到页面底部时,会自动加载更多内容,而不需要点击“加载更多”按钮。
以下是一个使用JavaScript实现下滑加载更多的简单示例:
<!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 class="item">Item 3</div>
</div>
<div id="loading" style="display: none;">Loading...</div>
<script>
let loading = false;
const content = document.getElementById('content');
const loadingIndicator = document.getElementById('loading');
function loadMoreContent() {
if (loading) return;
loading = true;
loadingIndicator.style.display = 'block';
// 模拟异步加载数据
setTimeout(() => {
for (let i = 0; i < 3; i++) {
const newItem = document.createElement('div');
newItem.className = 'item';
newItem.textContent = `Item ${content.children.length + 1}`;
content.appendChild(newItem);
}
loadingIndicator.style.display = 'none';
loading = false;
}, 1000);
}
window.addEventListener('scroll', () => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 50) {
loadMoreContent();
}
});
// 初始加载一些内容
loadMoreContent();
</script>
</body>
</html>
loading
变量),在加载过程中将其置为true
,加载完成后置为false
。下滑加载更多是一种提升用户体验的技术,通过合理实现可以有效减少用户操作步骤,提高页面加载效率。在实际应用中需要注意性能优化和兼容性问题,确保用户体验的流畅性。
领取专属 10元无门槛券
手把手带您无忧上云