實現下拉刷新主要分爲三步:
HTML代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>下拉刷新</title> <style type="text/css"> html,body, header,p,main,span,ul,li { margin: 0; padding: 0; } #refreshContainer li { background-color: rgba(5, 143, 62, 0.603); margin-bottom: 1px; padding: 30px 10px; } .refreshText { position: absolute; width: 100%; line-height: 80px; text-align: center; left: 0; top: 0; transform: translateY(-80px); } </style> </head> <body> <div class="parent"> <p class="refreshText"></p> <ul id="refreshContainer"> <li>000</li> <li>111</li> <li>222</li> <li>333</li> <li>444</li> <li>555</li> <li>666</li> <li>777</li> <li>888</li> <li>999</li> </ul> </div> </body> </html>
JS代碼實現
<script type="text/javascript"> window.onload = function () { let container = document.querySelector('#refreshContainer'); let refreshText = document.querySelector('.refreshText'); let parent = document.querySelector('.parent'); let startY = 0; //手指觸摸最開始的Y座標 let endY = 0; //手指結束觸摸時的Y座標 let flag = false; //下拉刷新是否達到了臨界值 parent.addEventListener('touchstart', function (e) { startY = e.touches[0].pageY; }); parent.addEventListener('touchmove', function (e) { if (isTop() && (e.touches[0].pageY - startY) > 50) { flag = true; document.body.style.overflow='hidden'; refreshText.style.height = "80px"; parent.style.transform = "translateY(80px)"; parent.style.transition = "all ease 0.5s"; refreshText.innerHTML = "釋放當即刷新..."; } }); //鬆開手指 parent.addEventListener('touchend', function (e) { if (isTop() && flag) { refreshText.innerHTML = "正在刷新..."; //進行更新操做,更新結束後,結束下拉刷新 setTimeout(function () { parent.style.transform = "translateY(0)"; document.body.style.overflow = 'auto'; }, 2000); } }); //scrollTop沒有滾過 function isTop() { let t = document.documentElement.scrollTop || document.body.scrollTop; return t === 0 ? true : false; } } </script>
注意 body 的 overflow 屬性設置。javascript
謝謝您花費寶貴的時間閱讀本文,若是本文給了您一點幫助或者是啓發,那麼不要吝嗇你的贊和Star哈,您的確定是我前進的最大動力。https://github.com/YvetteLau/...css