本文提供一個輕量、無外掛依賴的 jQuery 範例,實作左側選單 div 透過右側分隔條拖曳調整寬度,支援視窗自適應高度,程式碼結構清晰易於擴充。
<!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>
mousedown 於分隔條記錄起始 X 座標與選單寬度。mousemove 計算位移 dx,更新選單寬度 (限制最小/最大值)。mouseup 移除文件層級事件監聽,避免洩漏。.on('mousemove.drag') 命名空間方便精確移除。box-sizing: border-box 確保寬度含邊框。localStorage 記住使用者偏好寬度。transition: width 0.1s 提升手感。此範例不依賴 jQuery UI 或第三方拖曳庫,核心邏輯約 30 行,適合嵌入既有專案快速實作可調整面板佈局。