美文网首页
鼠标拖动改变侧边栏的宽度

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

作者: 武汉前端任金杰 | 来源:发表于2023-05-04 14:19 被阅读0次
    <!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

    相关文章

      网友评论

          本文标题:鼠标拖动改变侧边栏的宽度

          本文链接:https://www.haomeiwen.com/subject/xwpxsdtx.html