创建无限滚动页面的关键是使用JavaScript监听滚动事件,当滚动到页面底部时,动态加载更多内容。以下是一般的实现步骤:
let currentPage = 1;
window
对象的scroll
事件。例如:window.addEventListener('scroll', loadMoreContent);
loadMoreContent
函数中,判断是否已经滚动到了页面底部。可以通过比较window
对象的scrollY
和document
对象的offsetHeight
和innerHeight
来判断。例如:function loadMoreContent() {
if (window.scrollY + window.innerHeight >= document.offsetHeight) {
// 加载更多内容
}
}
function loadMoreContent() {
if (window.scrollY + window.innerHeight >= document.offsetHeight) {
// 加载更多内容
const xhr = new XMLHttpRequest();
xhr.open('GET', `http://example.com/api/content?page=${currentPage+1}`);
xhr.onload = function() {
// 处理返回的数据,将新内容添加到页面中
currentPage++;
}
xhr.send();
}
}
function loadMoreContent() {
if (window.scrollY + window.innerHeight >= document.offsetHeight) {
// 加载更多内容
const xhr = new XMLHttpRequest();
xhr.open('GET', `http://example.com/api/content?page=${currentPage+1}`);
xhr.onload = function() {
const data = JSON.parse(xhr.responseText);
const contentList = document.querySelector('#content-list');
data.forEach(item => {
const li = document.createElement('li');
li.textContent = item.title;
contentList.appendChild(li);
});
currentPage++;
}
xhr.send();
}
}
使用以上步骤,可以实现无限滚动页面。关键在于监听滚动事件、判断是否滚动到页面底部、动态加载内容和将新内容添加到页面中。