```html
核心CSS样式需定义页面容器和单页的定位与过渡效果,确保页面切换时平滑过渡:
```css .page-container { position: relative; height: 100vh; overflow: hidden; } .page { position: absolute; top: 0; left: 0; width: 100%; height: 100%; transition: transform 0.5s cubic-bezier(0.36, 0.66, 0.04, 1); transform: translateY(100%); } .page.active { transform: translateY(0); } .page.prev { transform: translateY(-100%); } ```
滑动检测与事件监听 通过触摸事件touch或鼠标滚轮事件wheel捕捉用户滑动行为,判断滑动方向和距离,触发页面切换逻辑。触摸事件处理移动端
监听`touchstart`记录初始位置,`touchmove`跟踪滑动过程,`touchend`判断滑动方向:```javascript let startY = 0; let endY = 0; const pages = document.querySelectorAll('.page'); let currentIndex = 0;
document.addEventListener('touchstart', (e) => { startY = e.touches[0].clientY; });
document.addEventListener('touchmove', (e) => { endY = e.touches[0].clientY; });
document.addEventListener('touchend', () => { const diff = startY - endY; // 向上滑动下一页,阈值50px避免误触 if (diff > 50 && currentIndex < pages.length - 1) { pages[currentIndex].classList.remove('active'); pages[currentIndex].classList.add('prev'); currentIndex++; pages[currentIndex].classList.add('active'); } // 向下滑动上一页 else if (diff < -50 && currentIndex > 0) { pages[currentIndex].classList.remove('active'); pages[currentIndex].classList.add('next'); currentIndex--; pages[currentIndex].classList.remove('prev'); pages[currentIndex].classList.add('active'); } }); ```
鼠标滚轮适配PC端
通过`wheel`事件兼容PC端滑动,`deltaY`判断滚动方向:```javascript document.addEventListener('wheel', (e) => { // 向下滚动对应移动端向上滑动,下一页 if (e.deltaY > 0 && currentIndex < pages.length - 1) { pages[currentIndex].classList.remove('active'); pages[currentIndex].classList.add('prev'); currentIndex++; pages[currentIndex].classList.add('active'); } // 向上滚动上一页 else if (e.deltaY < 0 && currentIndex > 0) { pages[currentIndex].classList.remove('active'); pages[currentIndex].classList.add('next'); currentIndex--; pages[currentIndex].classList.remove('prev'); pages[currentIndex].classList.add('active'); } }); ```
动画细节优化 为增强交互体验,可添加滑动过程中的实时反馈,如页面随手指移动偏移:```javascript document.addEventListener('touchmove', (e) => { endY = e.touches[0].clientY; const diff = startY - endY; // 向上滑动时,当前页上移,下一页跟随 if (diff > 0 && currentIndex < pages.length - 1) { pages[currentIndex].style.transform = `translateY(-${diff}px)`; pages[currentIndex + 1].style.transform = `translateY(${100 - diff / window.innerHeight * 100}%)`; } // 向下滑动时,当前页下移,上一页跟随 else if (diff < 0 && currentIndex > 0) { pages[currentIndex].style.transform = `translateY(${-diff}px)`; pages[currentIndex - 1].style.transform = `translateY(${-100 + (-diff) / window.innerHeight * 100}%)`; } }); ```
应用场景与扩展 该方案可广泛应用于活动宣传页、产品介绍册、个人简历等多屏内容展示场景。通过调整`transition`的`timing-function`如`ease-out`、`cubic-bezier`,可实现不同风格的动画曲线,配合页面内容的渐显、缩放等效果,进一步提升视觉层次感。通过上述代码,即可实现H5页面上下滑动切换的核心功能,兼顾移动端触摸与PC端鼠标操作,确保用户在不同设备上均能获得流畅的交互体验。
