首页 > 解决方案 > 如何使用鼠标滚轮使 div 可横向滚动?

问题描述

当我将鼠标悬停而不是滚动整个页面(使用鼠标滚轮)时,我想在 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>

标签: htmljquerycss

解决方案


您可以通过将容器元素旋转 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-horizo​​ntal-scrolling/


推荐阅读