jQuery scroll事件實現監控滾動條分頁示例
阿新 • • 發佈:2019-01-06
scroll事件適用於window物件,但也可滾動iframe框架與CSS overflow屬性設定為scroll的元素。
$(document).ready(function () { //本人習慣這樣寫了
$(window).scroll(function () {
//$(window).scrollTop()這個方法是當前滾動條滾動的距離
//$(window).height()獲取當前窗體的高度
//$(document).height()獲取當前文件的高度
var bot = 50; //bot是底部距離的高度
if ((bot + $(window).scrollTop()) >= ($(document).height() - $(window).height())) {
//當底部基本距離+滾動的高度〉=文件的高度-窗體的高度時;
//我們需要去非同步載入資料了
$.getJSON("url", { page: "2" }, function (str) { alert(str); });
}
});
});
注意:(window).height()和(document).height()的區別
jQuery(window).height()代表了當前可見區域的大小,而jQuery(document).height()則代表了整個文件的高度,可視具體情況使用.
注意當瀏覽器視窗大小改變時(如最大化或拉大視窗後) jQuery(window).height() 隨之改變,但是jQuery(document).height()是不變的。
$(document).scrollTop() 獲取垂直滾動的距離 即當前滾動的地方的視窗頂端到整個頁面頂端的距離
$(document).scrollLeft() 這是獲取水平滾動條的距離
要獲取頂端 只需要獲取到scrollTop()==0的時候 就是頂端了
要獲取底端 只要獲取scrollTop()>=$(document).height()-$(window).height() 就可以知道已經滾動到底端了
$(document).height() //是獲取整個頁面的高度
$(window).height() //是獲取當前 也就是你瀏覽器所能看到的頁面的那部分的高度 這個大小在你縮放瀏覽器視窗大小時 會改變 與document是不一樣的 根據英文應該也能理解吧
自己做個實驗就知道了
複製程式碼程式碼如下:
$(document).scroll(function(){
$("#lb").text($(document).scrollTop());
})
<span id="lb" style="top:100px;left:100px;position:fixed;"></span><!--一個固定的span標記 滾動時方便檢視-->