類似微博,新浪新聞的評論等,都採用了這方法。
關鍵代碼:
var stop=true;
$(window).scroll(function(){
totalheight = parseFloat($(window).height()) + parseFloat($(window).scrollTop());
if($(document).height() <= totalheight){
if(stop==true){
stop=false;
$.post("ajax.php", {start:1, n:50},function(txt){
$("#Loading").before(txt);
stop=true;
},"text");
}
}
});
HTML:
<div id="Loading">Loading...</div>
實現方法是比較頁面總高度和下滾高度以判斷是否到達底端,若到達底端則通過ajax讀取更多的內容,用before插入到Loading之前。
stop參數是考慮到ajax讀取耗時,防止在一次ajax讀取過程中多次觸發事件,造成多次載入內容。
下面為你推薦 10 個 jQuery 的無限滾動的外掛程式:
1. jQuery ScrollPagination
jQuery ScrollPagination plugin 是一個 jQuery 實現的支援無限滾動式載入資料的外掛程式。
2. jQuery Screw
Screw (scroll + view) 是一個 jQuery 外掛程式當使用者滾動頁面的時候載入內容,是一個無限滾動翻頁的外掛程式。
3. AutoBrowse jQuery Plugin
Autobrowse jQuery Plugin 外掛程式在使用者滾動頁面的時候自動通過 Ajax 載入更多內容,使用瀏覽器內建緩衝。
4. Scroll Extend Plugin
scrollExtend 外掛程式用來在頁面滾動到螢幕底部時自動載入內容並追加 DOM 元素到頁面底部,該外掛程式其最初目的是為了跟 WordPress 整合。
5. Infinite Scroll
用了這個外掛程式,使用者訪問你的網站就不用翻頁啦!實際上它是預讀了後續頁的內容並將其直接添加到了當前頁面。
6. Load Content While Scrolling With jQuery
該外掛程式可協助非常快速的載入頁面的更多內容
7. Triggered Infinite Scroll
Triggered Infinite Scroll 是一個 Twitter 風格的自訂觸發器,不過它不是自動的。
8. Infinite Ajax Scroll, a jQuery Plugin
Infinite Ajax Scroll 可將你現有的網頁變成支援無限滾動的頁面,無需太麻煩就可搞定。
9. Infinite Scrolling jQuery Plugin
InfiniScroll 原先是一個 jQuery 外掛程式,用於部落格的文章列表顯示,不過現在已經不止這些了。
10. Unlimited Scroll using the Twitter API