React中如何实现无滚动条的局部横向滚动(整合至常规滚动视图)
实现常规滚动流中的横向无滚动条区域
不用jQuery或Framer Motion,纯HTML+CSS+原生JS就能实现你要的效果——页面整体纵向滚动,当滚动到指定区域时自动切换为横向滚动,且无任何滚动条或控制柄,保持滚动连贯性。
实现代码
HTML结构
<!-- 上方常规纵向滚动内容 --> <div class="section"> <p>向下滚动查看横向区域</p> </div> <!-- 横向滚动区域 --> <div class="horizontal-container"> <div class="horizontal-content"> <div class="horizontal-card">卡片1</div> <div class="horizontal-card">卡片2</div> <div class="horizontal-card">卡片3</div> <div class="horizontal-card">卡片4</div> <div class="horizontal-card">卡片5</div> <div class="horizontal-card">卡片6</div> <div class="horizontal-card">卡片7</div> </div> </div> <!-- 下方常规纵向滚动内容 --> <div class="section"> <p>横向区域已滚动完成</p> </div>
CSS样式
* { margin: 0; padding: 0; box-sizing: border-box; } /* 常规纵向滚动区块,占满一屏高度 */ .section { height: 100vh; display: flex; align-items: center; justify-content: center; background: #f5f5f5; font-size: 1.2rem; } /* 横向滚动容器:隐藏溢出内容(即滚动条),固定高度 */ .horizontal-container { height: 100vh; overflow: hidden; position: relative; background: #e8e8e8; } /* 横向内容容器:flex横向排列,宽度自适应所有子元素 */ .horizontal-content { display: flex; height: 100%; align-items: center; gap: 2rem; padding: 0 2rem; /* 禁止用户手动拖动横向内容,完全由页面滚动控制 */ pointer-events: none; } /* 横向卡片样式 */ .horizontal-card { width: 320px; height: 85%; background: #2196f3; color: white; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; box-shadow: 0 4px 12px rgba(0,0,0,0.15); } /* 彻底隐藏各浏览器的滚动条 */ .horizontal-container::-webkit-scrollbar { display: none; } .horizontal-container { -ms-overflow-style: none; scrollbar-width: none; }
原生JS逻辑
const horizontalContainer = document.querySelector('.horizontal-container'); const horizontalContent = document.querySelector('.horizontal-content'); // 计算横向内容可滚动的最大距离(内容总宽 - 容器宽度) const maxScrollDistance = horizontalContent.offsetWidth - horizontalContainer.offsetWidth; window.addEventListener('scroll', () => { const containerRect = horizontalContainer.getBoundingClientRect(); // 当横向容器进入视口范围时,开始处理滚动映射 if (containerRect.top <= window.innerHeight && containerRect.bottom >= 0) { // 计算页面滚动到容器区域的进度比例 const scrollProgress = (window.innerHeight - containerRect.top) / containerRect.height; // 将纵向滚动比例转化为横向滚动距离,不超过最大可滚动值 const targetScrollX = Math.min(scrollProgress * maxScrollDistance, maxScrollDistance); // 应用横向滚动 horizontalContainer.scrollLeft = targetScrollX; } });
核心原理
- 用CSS隐藏横向容器的滚动条,通过
overflow: hidden和浏览器专属滚动条隐藏样式实现 - 监听页面纵向滚动事件,当横向容器进入视口时,将纵向滚动的进度比例映射为横向容器的滚动距离
- 用
pointer-events: none禁止用户手动拖动横向内容,确保滚动完全由页面纵向滚动控制,保持连贯性
内容的提问来源于stack exchange,提问作者Amir B
相关产品推荐
相关产品推荐

