首先說明,下拉刷新有兩種情況:
一,重新刷新整個頁面.window.location.reload(),這種方式也可以做到,前提是進入頁面也是直接從后台取數據,這種方法較簡單;
二,下拉后不刷新頁面,只是向后台發送ajax請求,這種情況就復雜點,會存在服務端返回數據重復的情況,這個時候一般需要服務端返回一個參數,供客戶端判斷;
下面是自己js手寫下拉刷新代碼:(一些博客、論壇有別人寫好的,可修改使用)
css
.loading { display: inline-block; height: 15px; width: 15px; border-radius: 100%; margin: 6px; border: 2px solid #666; border-bottom-color: transparent; vertical-align: middle; -webkit-animation: rotate 0.75s linear infinite; animation: rotate 0.75s linear infinite; } @-webkit-keyframes rotate { 0% { -webkit-transform: rotate(0deg); } 50% { -webkit-transform: rotate(180deg); } 100% { -webkit-transform: rotate(360deg); } } @keyframes rotate { 0% { transform: rotate(0deg); } 50% { transform: rotate(180deg); } 100% { transform: rotate(360deg); } }
js
1 function update(element) { 2 var start = 0, 3 end = 0, 4 ele = $(element)[0];//DOM對象轉化為jQuery對象 5 ele.addEventListener("touchstart", touchstart, false); 6 ele.addEventListener("touchmove", touchmove, false); 7 ele.addEventListener("touchend", touchend, false); 8 9 $('<div class="update">↓下拉刷新</div>').prependTo($("body")); 10 11 function touchstart(ev) { 12 var touch = ev.targetTouches[0]; 13 start = touch.pageY; 14 } 15 16 function touchmove(ev) { 17 var touch = ev.targetTouches[0]; 18 end = start - touch.pageY; 19 $(this).css("top", (-end + "px")) 20 if(end < 0 && $(document).scrollTop() == 0) { 21 $(".update").show(); 22 end > -60 ? $(".update").html('↓下拉刷新') : $(".update").html('↑釋放更新 '); 23 } 24 } 25 26 function touchend(ev) { 27 if(parseInt(end) < 0 && $(document).scrollTop() == 0) { 28 $(".update").html('<span class="loading"></span>加載中...'); 29 //GetList(obj);向后台請求數據 30 window.location.reload();//刷新整個頁面 31 setTimeout(function() { 32 $(".update").remove(); 33 ele.css('top',0); 34 }, 2500); 35 } 36 } 37 }