現在很多網站流行下拉卷軸後動態載入資料,用來取代分頁選單,其實除非是討論區型的網站,像是新聞之類的資料很少有人會去點選分頁到後面的內容,今天自己實作一下這樣的方式。
其實原理很簡單,偵測一下卷軸是否到底,到底的話偵測最後一筆資料的 id,ajax 去撈取大於此 id 的資料回傳 DOM 後塞入內容,若想要有緩衝不想到底的話,可以於判斷高度的公式扣除所需要的像素範圍即可。
scroll.html
infinite scroll
1
2
scroll.js
$(function() {
var $c = $('#container'),
$id = null;
// if the content is smaller than window's height
// run infinite function at beginning
if ($c.height() <= $(window).height()) {
infiniteScroll();
}
// check if scroll to the bottom
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
infiniteScroll();
}
});
// dynamic load the data
function infiniteScroll() {
$id = $c.find('div:last').prop('id');
$.post('scroll.php', {id: $id}, function($res) {
$c.append($res);
});
}
});
scroll.php
$num = (int)$_POST['id'];
for ($i = 0; $i < 3; $i++) {
$num++;
echo ''.$num.'';
}
1 則留言:
很好,正在測試
但好像沒有設定loader.gif
張貼留言