js实现上划翻页
监听触摸事件
通过监听 touchstart、touchmove 和 touchend 事件来捕捉用户滑动行为。记录触摸起始位置和移动距离,判断是否为有效的上滑动作。
let startY = 0;
let endY = 0;
document.addEventListener('touchstart', (e) => {
startY = e.touches[0].clientY;
});
document.addEventListener('touchmove', (e) => {
endY = e.touches[0].clientY;
});
判断滑动方向
在 touchend 事件中计算垂直滑动距离和方向。若滑动距离超过阈值且方向向上,则触发翻页逻辑。

document.addEventListener('touchend', () => {
const distance = endY - startY;
const isSwipeUp = distance < -50; // 阈值设为50px
if (isSwipeUp) {
goToNextPage();
}
});
翻页动画效果
使用 CSS 过渡或动画实现平滑的翻页效果。通过添加/移除类名控制页面切换动画。
function goToNextPage() {
const currentPage = document.querySelector('.page.active');
const nextPage = document.querySelector('.page:not(.active)');
currentPage.classList.remove('active');
nextPage.classList.add('active');
}
CSS 样式示例
为页面容器和动画效果添加基础样式,确保滑动时视觉连贯性。

.page {
position: absolute;
width: 100%;
height: 100%;
transition: transform 0.3s ease;
}
.page.active {
transform: translateY(0);
}
.page:not(.active) {
transform: translateY(100%);
}
边界条件处理
禁止在页面过渡期间重复触发翻页,可通过标志位控制。
let isAnimating = false;
function goToNextPage() {
if (isAnimating) return;
isAnimating = true;
// 翻页逻辑...
setTimeout(() => {
isAnimating = false;
}, 300); // 匹配CSS动画时长
}
多页场景扩展
对于多页场景,可通过数组或自定义属性管理页面索引。
let currentIndex = 0;
const pages = document.querySelectorAll('.page');
function goToNextPage() {
if (currentIndex >= pages.length - 1) return;
pages[currentIndex].classList.remove('active');
currentIndex++;
pages[currentIndex].classList.add('active');
}





