<!DOCTYPE=html> <html> <head> <script src="jquery-1.4.2.min.js" type="text/javascript"></script> </head> <body> <div>下拉加載更多</div> <div class="main" style="height:700px;overflow:auto;"> <div class="child" style='border:1px solid red;margin-top:20px;color:grey;height:800px' ></div> </div> </body> <script type="text/javascript"> $(document).ready(function(){ $(".main").unbind("scroll").bind("scroll", function(e){ var sum = this.scrollHeight; if (sum <= $(this).scrollTop() + $(this).height()) { $(".main").append($(".child").clone()); } }); }); </script> </html>
如果等滾動條拉到底部時再加載,會影響用戶體驗。因為一般動態加載的時候都需要向服務端請求資源,這時需要時間。一個更佳的方式是,當滾動條距離底部一定距離(C)時,就動態加載更多,向服務端請求資源。也就是預加載,預讀取。公式如下。
this.scrollHeight - C <= $(this).scrollTop() + $(this).height()