【问题标题】:How to make div scrollable sideways using mousewheel?如何使用鼠标滚轮使 div 可横向滚动?
【发布时间】:2021-05-02 16:05:53
【问题描述】:

当我将鼠标悬停时,我想在 div 内滚动,而不是滚动整个页面(使用鼠标滚轮)。这通常适用于overflowY(上下)滚动,但不适用于overflowX(横向)

我不知道它是否可以只使用 CSS 或者它是否需要 JavaScript 或 jQuery

我做了一个例子,其中一个 div 有一个 X 轴溢出和滚动,当你指向它并使用你的滚轮时,它会滚动页面而不是你悬停的 div。

.parent {
    background: red;
    height: 100px;
    width: 100px;
    display: flex;
    overflow-x: scroll;
}

.child {
    background: blue;
    border: 1px solid black;
    margin: 3px;
    height: 30px;
    width: 50px;
    flex-shrink: 0;
}

body {
    height: 200vh;
}
<body>
    <div class="parent">
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
    </div>
</body>

【问题讨论】:

标签: html jquery css


【解决方案1】:

您可以通过将容器元素旋转 90 度来实现。检查这个例子:

HTML

<div class="horizontal-scroll-wrapper squares">
  <div>item 1</div>
  <div>item 2</div>
  <div>item 3</div>
  <div>item 4</div>
  <div>item 5</div>
  <div>item 6</div>
  <div>item 7</div>
  <div>item 8</div>
</div>

<div class="horizontal-scroll-wrapper  rectangles">
  <div>item 1</div>
  <div>item 2</div>
  <div>item 3</div>
  <div>item 4</div>
  <div>item 5</div>
  <div>item 6</div>
  <div>item 7</div>
  <div>item 8</div>
</div>

CSS:

::-webkit-scrollbar{width:2px;height:2px;}
::-webkit-scrollbar-button{width:2px;height:2px;}

div{
  box-sizing:border-box;
}

body {
  background: #111;
}

.horizontal-scroll-wrapper{
  position:absolute;
  display:block;
  top:0;
  left:0;
  width:80px;
  max-height:500px;
  margin:0;
  background:#abc;
  overflow-y:auto;
  overflow-x:hidden;
  transform:rotate(-90deg) translateY(-80px);
  transform-origin:right top;
}
.horizontal-scroll-wrapper > div{
  display:block;
  padding:5px;
  background:#cab;
  transform:rotate(90deg);
  transform-origin: right top;
}

.squares{
  padding:60px 0 0 0;
}

.squares > div{
  width:60px;
  height:60px;
  margin:10px;
}

.rectangles{
  top:100px;
  padding:100px 0 0 0;
}
.rectangles > div{
  width:140px;
  height:60px;
  margin:50px 10px;
  padding:5px;
  background:#cab;
  transform:rotate(90deg) translateY(80px);
  transform-origin: right top;
}

在此处查看其他示例: https://css-tricks.com/pure-css-horizontal-scrolling/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 2018-05-13
    • 2010-12-08
    • 2017-02-27
    • 1970-01-01
    相关资源
    最近更新 更多