鼠标横向拖动滚动条 - 简单实现

1638351439(1).png
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>横向拖动</title>
</head>
<style>
  .box {
    width: 400px;
    height: 167px;
    margin: 300px auto 0;
    border: 1px solid salmon;
    overflow: auto;
    font-size: 0;
    white-space: nowrap;
    cursor: pointer;
    user-select: none;
  }

  .box>div {
    display: inline-block;
    width: 30px;
    height: 140px;
    margin: 5px 15px;
    background-color: sandybrown;
  }
</style>

<body>
  <div class="box" id="box">
    <div>0</div>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
    <div>9</div>
    <div>10</div>
    <div>11</div>
    <div>12</div>
    <div>13</div>
    <div>14</div>
    <div>15</div>
    <div>16</div>
    <div>17</div>
    <div>18</div>
    <div>19</div>
  </div>
  <script>
    (function () {
      var $box = document.getElementById('box')
      var left = 0;
      var oldY = 0;
      var handleMove = function (e) {
        handleChangeScroll(e.clientX)
      }

      var handleChangeScroll = (clientX) => {
        var x = left + (oldY - clientX)
        if (x < 0) x = 0;
        $box.scrollTo(x, 0)
      }

      $box.addEventListener('mousedown', function (e) {
        oldY = e.clientX;
        left = $box.scrollLeft;
        document.addEventListener('mousemove', handleMove)
      });

      document.addEventListener('mouseup', function () {
        document.removeEventListener('mousemove', handleMove)
      })


    })()
  </script>
</body>

</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容