CSS横向滚动(overflow-x: scroll)失效:鼠标滚轮无响应
解决横向滚动容器鼠标滚轮无响应问题
问题原因
你的容器设置了横向滚动,但浏览器默认鼠标滚轮事件对应纵向滚动,因此上下滚轮操作不会触发容器的横向滚动行为。
解决方案:JavaScript监听滚轮事件
给容器添加滚轮事件监听,将纵向的滚轮偏移量转为横向滚动位移,实现上下滚轮控制横向滚动:
const container = document.querySelector('.container'); container.addEventListener('wheel', (e) => { e.preventDefault(); container.scrollLeft += e.deltaY; });
将这段代码放在HTML的</body>标签前即可,它会拦截滚轮事件,把上下滚动的动作转化为容器的横向滚动。
如果想要更顺滑的滚动体验,可以给容器添加scroll-behavior: smooth的CSS属性:
body .container { width: 100%; height: 100%; scroll-snap-type: x mandatory; overflow-x: scroll; display: flex; scroll-behavior: smooth; /* 开启平滑滚动 */ }
完整可运行代码
body { width: 100vw; height: 100vh; margin: 0; } body .container { width: 100%; height: 100%; scroll-snap-type: x mandatory; overflow-x: scroll; display: flex; scroll-behavior: smooth; } body .container section { flex: none; display: flex; justify-content: center; align-items: center; width: 100vw; height: 100vh; scroll-snap-align: start; } body .container section:nth-of-type(1) { background-color: rgb(33, 59, 27); color: green; } body .container section:nth-of-type(2) { background-color: rgb(45, 42, 39); color: rgb(182, 216, 182); } body .container section:nth-of-type(3) { background-color: rgb(52, 41, 33); color: rgb(87, 33, 233); } body .container section h1 { font-family: "Courier New", Courier, monospace; font-size: 10em; } body .container section p { font-size: 12px; }
<!-- main wrapper of the content for the whole webpage --> <div class="container"> <!-- sections of the web page --> <section> <h1>Page1</h1> <p>random text</p> </section> <section> <h1>Page2</h1> </section> <section> <h1>Page3</h1> </section> </div> <script> const container = document.querySelector('.container'); container.addEventListener('wheel', (e) => { e.preventDefault(); container.scrollLeft += e.deltaY; }); </script>
注意:e.preventDefault()会阻止默认的纵向滚动行为,确保滚轮只作用于横向容器。如果页面存在其他需要纵向滚动的区域,需调整监听逻辑避免冲突。
内容的提问来源于stack exchange,提问作者golfcat
相关产品推荐
相关产品推荐

