移動端的下拉刷新是一個很常見的功能,也有許多開源庫實現了這個功能,不過爲了學習,仍是先本身寫一個例子學習一下。其中用到了一些touch事件和一些DOM屬性CSS3屬性。直接上代碼,代碼裏面有註釋。javascript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Document</title> <style type="text/css"> html, body, header, div, main, p, span, ul, li { margin: 0; padding: 0; } #refreshContainer li { background-color: #eee; margin-bottom: 1px; padding: 20px 10px; } .refreshText { position: absolute; width: 100%; line-height: 50px; text-align: center; left: 0; top: 0; transform: translateY(-50px); } </style> </head> <body> <main class="parent"> <p class="refreshText"></p> <ul id="refreshContainer"> <li>111</li> <li>222</li> <li>333</li> <li>444</li> <li>555</li> <li>111</li> <li>222</li> <li>333</li> <li>444</li> <li>555</li> <li>111</li> <li>222</li> <li>333</li> <li>444</li> <li>555</li> </ul> </main> <script type="text/javascript"> window.onload = function(){ //1.獲取到列表的dom,刷新顯示部分的dom,列表父容器的dom let container = document.querySelector('#refreshContainer'); let refreshText = document.querySelector('.refreshText'); let parent = document.querySelector('.parent'); //2.定義一些須要經常使用的變量 let startY = 0;//手指觸摸最開始的Y座標 let endY = 0;//手指結束觸摸時的Y座標 //3.給列表dom監聽touchstart事件,獲得起始位置的Y座標 parent.addEventListener('touchstart',function(e){ startY = e.touches[0].pageY; }); //4.給列表dom監聽touchmove事件,當移動到必定程度須要顯示上面的文字 parent.addEventListener('touchmove',function (e) { if(isTop() && (e.touches[0].pageY-startY) > 0){ console.log('下拉了'); refreshText.style.height = "50px"; parent.style.transform = "translateY(50px)"; parent.style.transition = "all ease 0.5s"; refreshText.innerHTML = "釋放當即刷新..."; } }); //5.給列表dom監聽touchend事件,此時說明用戶已經鬆開了手指,應該進行異步操做了 parent.addEventListener('touchend',function (e) { if(isTop()){ refreshText.innerHTML = "正在刷新..."; setTimeout(function(){ parent.style.transform = "translateY(0)"; console.log('成功刷新'); },2000) } return; }) function isTop(){ var t = document.documentElement.scrollTop||document.body.scrollTop; return t === 0 ? true : false; } } </script> </body> </html>