下拉刷新實現原理
實現下拉刷新主要分爲三步:
- 監聽原生touchstart事件,記錄其初始位置的值,e.touches[0].pageY;
- 監聽原生touchmove事件,記錄並計算當前滑動的位置值與初始位置值的差值,大於某個臨界值時,顯示下拉刷新頭,並將頁面的overflow屬性,設置爲false;
- 監聽原生touchend事件,若此時元素滑動已經最大值,則進行刷新操作,操作結束後,將頁面的overflow屬性,設置爲auto。
代碼實現
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 屬性設置。