DIV CSS 佈局教程網

拉動滾動條動態載入資料的 jQuery 實作
編輯:JQuery特效代碼     

「捲到底自動載入更多」是現代網頁常見的體驗。以下示範如何監聽捲動事件,在接近頁面底部時動態載入新資料。

. 代碼如下:

<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>拉動滾動條加載數據</title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var i = 4;
$(window).bind("scroll", function (event)
{
// 滾動條到網頁頂部的高度,相容 ie、ff、chrome
var top = document.documentElement.scrollTop + document.body.scrollTop;
// 網頁的高度
var textheight = $(document).height();
// 網頁高度 - top - 當前視窗高度
if (textheight - top - $(window).height() <= 100) {
if (i >= 100) {
return; // 控制最大只能加載到 100
}
$('#div1').css("height", $(document).height() + 100);
i++;
// 可依實際情況取得動態資料載入到 div1 中
$('<div>' + i + '</div>').appendTo($('#div1'));
}
});
})
</script>
<style>
#div1 div
{
font-size: 100px;
background: #ccc;
margin-top: 5px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div style="height: 1000px;" id="div1">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</form>
</body>
</html>

關鍵在於判斷式 textheight - top - $(window).height() <= 100:當捲動後剩下的距離小於 100px(即將到底)時,就動態增加容器高度並載入新內容。實際應用時,把新增 div 的部分替換成向後端請求資料即可。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved