CSS 问题:水平滚动(overflow-x:scroll)不起作用
P粉295616170
P粉295616170 2024-03-29 16:06:18
[HTML讨论组]

我有 3 个“页面”,想要水平滚动它们。 我已经成功创建了一个水平滚动条,但是当我用鼠标滚轮向上/向下滚动时什么也没有发生。

这就是我的容器的样子:

body .container {
  width: 100%;
  height: 100%;
  scroll-snap-type: x mandatory;
  overflow-x: scroll;
  display: flex;
}

完整的 HTML + CSS:

body {
  width: 100vw;
  height: 100vh;
  margin: 0;
}

body .container {
  width: 100%;
  height: 100%;
  scroll-snap-type: x mandatory;
  overflow-x: scroll;
  display: flex;
}

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>

我尝试 Google 但没有找到任何解决方案...我从 YouTube 教程中获得了所有这些内容。

P粉295616170
P粉295616170

全部回复(1)
P粉621033928

这里需要使用一些 JavaScript,并且必须从容器中删除宽度和高度属性

const scrollContainer = document.querySelector(".container");

scrollContainer.addEventListener("wheel", (evt) => {
    evt.preventDefault();
    scrollContainer.scrollLeft += evt.deltaY;
});
body {
  width: 100vw;
  height: 100vh;
  margin: 0;
}


body .container {
  overflow-x: scroll;
  display: flex;
}

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;
}

Page1

random text

Page2

Page3

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号