天天看點

移動端滾動加載資料實作

模拟場景:移動端上劃到底,加載更多資料。

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
        //console.log(_h)
        if(scrollTop + _height >= _h){
            console.log('到底了')
            getImage();
        }
    })  
})