下拉刷新实现原理
实现下拉刷新主要分为三步:
- 监听原生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;
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 属性设置。
.