Vue 3反向水平滚动功能实现求助
反向水平滚动实现方案
核心逻辑修改
你需要补充滚轮事件处理函数,并添加触摸滑动的事件监听,以下是完整的实现代码:
模板部分(修改后)
<template> <BackgroundLayer /> <div class="layout-wrapper"> <div class="horizontal-container" @wheel="handleHorizontalScroll" @touchstart="handleTouchStart" @touchmove="handleTouchMove" > <div class="horizontal-section"> <ProjectsSection /> </div> <div class="horizontal-section"> <ContactSection /> </div> <div class="horizontal-section"> <HomeSection /> </div> </div> <footer> <p>© 2025 Onyedikachukwu Okonkwo</p> </footer> </div> </template>
Script部分(新增)
<script setup> import { ref } from 'vue' // 存储触摸起始的X坐标 const touchStartX = ref(0) // 处理鼠标滚轮事件 const handleHorizontalScroll = (e) => { e.preventDefault() // 阻止默认垂直滚动行为 // 反转滚轮方向:向上滚动→页面左移;向下滚动→页面右移 e.target.scrollLeft += e.deltaY } // 记录触摸起始位置 const handleTouchStart = (e) => { touchStartX.value = e.touches[0].clientX } // 处理触摸滑动 const handleTouchMove = (e) => { e.preventDefault() // 阻止默认滑动行为 const touchCurrentX = e.touches[0].clientX const diffX = touchStartX.value - touchCurrentX // 滑动逻辑:向左滑→页面左移;向右滑→页面右移 // 增加阈值避免误触 if (Math.abs(diffX) > 10) { e.target.scrollLeft += diffX touchStartX.value = touchCurrentX // 更新起始位置实现连续滑动 } } </script>
样式部分(优化后)
.horizontal-container { height: calc(100vh - 100px); width: auto; display: flex; flex-direction: row; align-items: center; overflow-x: scroll; scroll-snap-type: x mandatory; /* 提升滑动体验 */ scroll-behavior: smooth; -webkit-overflow-scrolling: touch; } .horizontal-container::-webkit-scrollbar { display: none; } .horizontal-section { width: 100vw; height: 100%; min-height: 100%; min-width: 100vw; display: flex; justify-content: center; align-items: center; color: #1a1a1a; scroll-snap-align: center; }
关键说明
- 滚轮事件:通过
e.deltaY获取滚轮方向,直接赋值给scrollLeft实现反向滚动,同时阻止默认垂直滚动行为。 - 触摸滑动:记录触摸起始X坐标,计算滑动差值,将差值加到
scrollLeft上实现对应方向滚动,添加阈值避免误触。 - 样式优化:添加平滑滚动和移动端触摸滚动优化属性,提升交互体验。
内容的提问来源于stack exchange,提问作者aye_K.O
相关产品推荐
相关产品推荐

