萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

jQuery 實作 Div 拖曳調整寬度:完整可執行範例

本文提供一個輕量、無外掛依賴的 jQuery 範例,實作左側選單 div 透過右側分隔條拖曳調整寬度,支援視窗自適應高度,程式碼結構清晰易於擴充。

完整 HTML + JS + CSS (單檔可執行)

<!DOCTYPE html>
<html style="height:100%;">
<head>
  <meta charset="UTF-8">
  <title>Div 拖曳調整寬度 Demo</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    html, body { height:100%; margin:0; padding:0; overflow:hidden; }
    #top { width:100%; height:80px; background:#eee; border-bottom:1px solid #ccc; }
    #menu { float:left; width:200px; height:100%; background:#f1f1f1; border-right:1px solid #ccc; box-sizing:border-box; }
    #splitter { float:left; width:5px; height:100%; background:#ccc; cursor:col-resize; user-select:none; }
    #rightbar { float:left; width:calc(100% - 205px); height:100%; background:#fff; overflow:auto; }
  </style>
</head>
<body>
  <div id="top">頂部區域 (固定 80px)</div>
  <div id="menu">左側選單</div>
  <div id="splitter"></div>
  <div id="rightbar">右側內容區</div>

  <script>
    $(function() {
      var $menu = $('#menu'), $splitter = $('#splitter'), $right = $('#rightbar');
      var startX, startMenuW;

      // 視窗高度自適應
      function resizeHeight() {
        var h = $(window).height() - $('#top').outerHeight();
        $menu.add($right).height(h);
      }
      resizeHeight();
      $(window).resize(resizeHeight);

      // 拖曳邏輯
      $splitter.on('mousedown', function(e) {
        startX = e.clientX;
        startMenuW = $menu.width();
        $(document).on('mousemove.drag', onDrag).on('mouseup.drag', onUp);
        e.preventDefault();
      });

      function onDrag(e) {
        var dx = e.clientX - startX;
        var newW = Math.max(100, Math.min(startMenuW + dx, $(window).width() - 150));
        $menu.width(newW);
        $right.width($(window).width() - newW - $splitter.width());
      }

      function onUp() {
        $(document).off('.drag');
      }
    });
  </script>
</body>
</html>

核心邏輯解析

  1. mousedown 於分隔條記錄起始 X 座標與選單寬度。
  2. mousemove 計算位移 dx,更新選單寬度 (限制最小/最大值)。
  3. mouseup 移除文件層級事件監聽,避免洩漏。
  4. 使用 .on('mousemove.drag') 命名空間方便精確移除。
  5. box-sizing: border-box 確保寬度含邊框。

擴充建議

  • 加入 localStorage 記住使用者偏好寬度。
  • 支援雙擊分隔條收合/展開選單。
  • 整合至 Vue/React 元件化架構。
  • 加入動畫過渡 transition: width 0.1s 提升手感。

此範例不依賴 jQuery UI 或第三方拖曳庫,核心邏輯約 30 行,適合嵌入既有專案快速實作可調整面板佈局。

copyright © 萬盛學電腦網 all rights reserved