You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 17:16:06