模擬場景:移動端上划到底,加載更多數據。
1、本例子基於jQuery實現。監聽滾動事件。
$(function(){
$(window).scroll(function(){
})
})
2、獲取滾動條到文檔頂部的距離,上圖scrollTop那段。原生JS可用document.documentElement.scrollTop獲取。
var scrollTop = Math.ceil($(this).scrollTop());
3、獲取可視區高度。原生JS可用document.documentElement.clientHeight獲取。
var _height = $(this).height()
4、獲取文檔總高度。原生JS用document.body.scrollHeight獲取
var _h = \((document).height(); 5、如果scrollTop+_height的距離大於等於_h,說明觸底了,再次請求數據追加到當前數據后面即可。 完整代碼如下:getImage()為請求數據的方法。 \)(function(){
getImage();
\((window).scroll(function(){ var scrollTop = Math.ceil(\)(this).scrollTop());//滾動條與上面的距離document.documentElement.scrollTop
var _height = $(this).height();//可視區高度document.documentElement.clientHeight
var _h = $(document).height();//總高度 document.body.scrollHeight
if(scrollTop + _height >= _h){
console.log('到底了')
getImage();
}
})
})