下拉刷新(Pull to Refresh):
1. 创建一个包含下拉刷新内容的容器,通常是一个`<div>`元素。
2. 监听`touchstart`、`touchmove`和`touchend`事件以追踪用户的滑动动作。
3. 当用户滑动超过一定的距离时,触发刷新操作,通常通过改变DOM元素的状态或添加加载动画。
4. 当数据加载完成后,通过JavaScript更新DOM内容,重置下拉刷新状态。
以下是一个简单的示例:
<!DOCTYPE html>
<html>
<head>
<style>
#refresh-container {
height: 60px;
overflow: hidden;
}
#refresh-text {
font-size: 50px;
}
</style>
</head>
<body>
<div id="refresh-container">
<div id="refresh-text">Pull down to refresh</div>
</div>
<script>
const refreshContainer = document.getElementById("refresh-container");
const refreshText = document.getElementById("refresh-text");
let isRefreshing = false;
let startY;
let currentY;
refreshContainer.addEventListener("touchstart", (e) => {
startY = e.touches[0].clientY;
console.log('用户触摸');
});
refreshContainer.addEventListener("touchmove", (e) => {
if (isRefreshing) return;
currentY = e.touches[0].clientY;
const distance = currentY - startY;
console.log('用户下拉多少',distance);
if (distance > 0) {
e.preventDefault();
refreshText.textContent = "Release to refresh";
}
});
refreshContainer.addEventListener("touchend", (e) => {
if (isRefreshing) return;
if (currentY > startY) {
isRefreshing = true;
refreshText.textContent = "Refreshing...";
console.log('用户停止触摸,开始刷新中。。。');
// Simulate data loading
setTimeout(() => {
isRefreshing = false;
refreshText.textContent = "Pull down to refresh";
console.log('刷新完成');
}, 2000);
}
});
</script>
</body>
</html>
原生实现下拉刷新