實現HTML5頁面上滑加載更多功能的方案:
1. 頁面結構
<div id="content-container">
<div class="item" v-for="(item, index) in items" :key="index">
<!-- 在這裏渲染單個數據項的內容 -->
</div>
</div>
<!-- 加載提示區域 -->
<div id="load-more" v-if="loadingMore">
<p>Loading...</p>
</div>
2. JavaScript(假設使用Vue.js作爲示例框架)
const app = new Vue({
el: '#app',
data() {
return {
items: [], // 存儲已加載的數據項
page: 1, // 當前請求頁碼
loadingMore: false, // 是否正在加載更多
hasMore: true, // 是否還有更多數據可供加載
};
},
mounted() {
this.fetchData();
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
},
methods: {
fetchData() {
this.loadingMore = true;
axios.get(`your-api-url?page=${this.page}&limit=15`)
.then(response => {
const newItems = response.data.items; // 假設API返回數據結構中包含一個名爲items的數組
if (newItems.length < 15) {
this.hasMore = false; // 如果本次加載數量不足15條,說明已無更多數據
}
this.items.push(...newItems);
this.page++;
this.loadingMore = false;
})
.catch(error => {
console.error('Error fetching more data:', error);
this.loadingMore = false;
});
},
handleScroll() {
const contentContainer = document.getElementById('content-container');
const threshold = 100;
const { scrollTop, offsetHeight, scrollHeight } = contentContainer;
const distanceFromBottom = scrollHeight - (scrollTop + offsetHeight);
if (!this.loadingMore && distanceFromBottom <= threshold && this.hasMore) {
this.fetchData();
}
},
},
});
解釋說明
-
頁面結構中,使用
div#content-container
來存放數據項,並通過v-for
循環遍歷items
數組進行渲染。同時,添加了一個div#load-more
用於顯示加載中的提示,其顯示與否由loadingMore
狀態控制。 -
JavaScript部分,我們創建了一個Vue實例,其中:
-
data
屬性定義了所需的狀態變量:items
存儲已加載的數據項,page
記錄當前請求的頁碼,loadingMore
表示是否正在加載更多,hasMore
標識是否還有更多數據可加載。 -
mounted
生命週期鉤子中,初始化時調用fetchData
方法加載第一頁數據,並監聽窗口的scroll
事件,綁定handleScroll
方法處理滾動行爲。 -
beforeDestroy
生命週期鉤子中,移除scroll
事件監聽器,防止內存泄漏。 -
methods
中定義了:-
fetchData
方法:負責發起Ajax請求,獲取下一頁數據。請求成功後,將新數據追加到items
數組,並更新頁碼和loadingMore
狀態。若本次加載數據不足15條,則設置hasMore
爲false
。若請求失敗,僅打印錯誤信息並恢復loadingMore
狀態。 -
handleScroll
方法:計算content-container
距底部的距離distanceFromBottom
。當距離小於等於閾值(100像素),且當前未處於加載狀態且仍有更多數據時,觸發fetchData
方法加載更多數據。
-
-
使用div
展示數據,通過Ajax動態加載,距離底部100像素時觸發加載,加載中顯示提示,加載失敗時不重試,每次加載15條數據。
歡迎關注公-衆-號【TaonyDaily】、留言、評論,一起學習。
Don’t reinvent the wheel, library code is there to help.
文章來源:劉俊濤的博客
若有幫助到您,歡迎點贊、轉發、支持,您的支持是對我堅持最好的肯定(_)