鼠标拖动改变侧边栏的宽度

<!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>Document</title>
    <style>
      body {
        margin: 0;
        position: relative;
        height: 100vh;
      }

      .menu-wrapper {
        position: absolute;
        left: 0;
        top: 0;
        height: 100%;
        width: 300px;
        background-color: #ccc;
      }

      .resize-bar {
        position: absolute;
        top: 0;
        right: 0px;
        width: 10px;
        height: 100%;
        cursor: col-resize;
        background-color: orange;
      }

      .content {
        margin-left: 300px;
        height: 100%;
        background-color: #999;
      }
    </style>
  </head>

  <body>
    <div class="menu-wrapper">
      <div class="resize-bar"></div>
    </div>
    <div class="content"></div>

    <script>
      let resizing = false
      const menu = document.querySelector('.menu-wrapper')
      const resizeBar = document.querySelector('.resize-bar')

      resizeBar.addEventListener('mousedown', () => {
        resizing = true
      })

      window.addEventListener('mousemove', (e) => {
        if (resizing) {
          e.preventDefault()
          e.stopPropagation()
          const { screenX } = e
          menu.style.width = screenX + 'px'
        }
      })

      window.addEventListener('mouseup', () => {
        resizing = false
      })
    </script>
  </body>
</html>

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

推荐阅读更多精彩内容