1. 程式人生 > >移動端滾動載入資料實現

移動端滾動載入資料實現

模擬場景:移動端上劃到底,載入更多資料。 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();
         }
   }) 

})