h5实现翻页
实现翻页的基本方法
在H5中实现翻页效果,可以通过多种方式完成。常见的包括使用CSS动画、JavaScript库或原生滚动事件监听。以下是几种具体实现方案。

使用CSS和JavaScript实现
通过CSS设置页面容器为全屏,利用transform属性实现滑动效果。JavaScript监听触摸或鼠标事件,控制页面切换。

<style>
.page-container {
width: 100vw;
height: 100vh;
overflow: hidden;
}
.page {
width: 100%;
height: 100%;
position: absolute;
transition: transform 0.5s ease;
}
</style>
<div class="page-container">
<div class="page" style="background: #f00;"></div>
<div class="page" style="background: #0f0;"></div>
<div class="page" style="background: #00f;"></div>
</div>
<script>
let currentPage = 0;
const pages = document.querySelectorAll('.page');
const totalPages = pages.length;
function goToPage(index) {
if (index < 0 || index >= totalPages) return;
currentPage = index;
pages.forEach((page, i) => {
page.style.transform = `translateY(${-currentPage * 100}%)`;
});
}
// 监听触摸事件
let startY;
document.addEventListener('touchstart', (e) => {
startY = e.touches[0].clientY;
});
document.addEventListener('touchend', (e) => {
const endY = e.changedTouches[0].clientY;
if (startY - endY > 50) goToPage(currentPage + 1); // 上滑
if (endY - startY > 50) goToPage(currentPage - 1); // 下滑
});
</script>
使用Swiper库快速实现
Swiper是一个流行的触摸滑动库,支持丰富的配置选项和动画效果。引入Swiper后只需简单配置即可实现翻页。
<link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css">
<script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide" style="background: #f00;">Slide 1</div>
<div class="swiper-slide" style="background: #0f0;">Slide 2</div>
<div class="swiper-slide" style="background: #00f;">Slide 3</div>
</div>
</div>
<script>
const swiper = new Swiper('.swiper-container', {
direction: 'vertical', // 垂直翻页
mousewheel: true, // 允许鼠标滚轮控制
});
</script>
监听滚动事件实现
通过监听window的滚动事件,结合页面高度计算当前页数。适合需要与原生滚动行为结合的翻页效果。
let currentScroll = 0;
const pageHeight = window.innerHeight;
window.addEventListener('scroll', () => {
const newScroll = window.scrollY;
const delta = newScroll - currentScroll;
if (delta > 50) {
window.scrollTo({
top: Math.floor(newScroll / pageHeight) * pageHeight + pageHeight,
behavior: 'smooth'
});
} else if (delta < -50) {
window.scrollTo({
top: Math.floor(newScroll / pageHeight) * pageHeight - pageHeight,
behavior: 'smooth'
});
}
currentScroll = newScroll;
});
注意事项
- 移动端需考虑触摸事件的兼容性,建议使用
touchstart和touchend而非click。 - 性能优化:大量DOM操作时使用
requestAnimationFrame避免卡顿。 - 无障碍访问:为翻页按钮添加ARIA标签,确保屏幕阅读器可识别操作意图。






