組織架構圖需支援節點自由拖拽、連線自動重繪、層級結構維護。本文展示基於 jQuery UI Draggable 的輕量實作:HTML 結構定義節點與連線、CSS 定位、JS 初始化拖拽、拖拽時即時更新連線座標。
<div id="orgChart" class="org-chart">
<div class="node" data-id="1">
<span class="label">總經理</span>
<div class="connector"></div> <!-- 連線錨點 -->
<div class="children">
<div class="node" data-id="2">...</div>
<div class="node" data-id="3">...</div>
</div>
</div>
</div>
.org-chart { position: relative; min-height: 500px; }
.node { position: absolute; min-width: 120px; padding: 8px 16px;
background: #fff; border: 1px solid #ccc; border-radius: 4px;
box-shadow: 0 2px 4px rgba(0,0,0,.1); cursor: move; }
.node.dragging { z-index: 999; opacity: .8; }
.connector { position: absolute; width: 2px; background: #999; }
.children { margin-left: 40px; margin-top: 20px; }
function initOrgChart() {
$('.node').draggable({
containment: '#orgChart',
handle: '.label', // 僅標題區可拖拽
start: (e, ui) => ui.helper.addClass('dragging'),
drag: (e, ui) => updateConnectors(ui.helper),
stop: (e, ui) => {
ui.helper.removeClass('dragging');
saveLayout(); // 儲存座標到後端/LocalStorage
}
});
}
function updateConnectors($movedNode) {
// 1. 更新該節點對父節點的連線
const $parentConnector = $movedNode.parent().closest('.node').find('> .connector');
drawConnector($parentConnector, $movedNode.find('> .connector'));
// 2. 更新該節點對所有子節點的連線
$movedNode.find('.children > .node').each((_, child) => {
drawConnector($movedNode.find('> .connector'), $(child).find('> .connector'));
});
}
function drawConnector($from, $to) {
const f = $from.offset(), t = $to.offset();
const x1 = f.left + $from.outerWidth()/2, y1 = f.top + $from.outerHeight();
const x2 = t.left + $to.outerWidth()/2, y2 = t.top;
// 簡單 L 型連線:垂直 → 水平 → 垂直
$from.css({ height: (y2 - y1) + 'px' }); // 假設 connector 為垂直線
// 實際專案建議用 SVG 或 Canvas 繪製正交/貝茲曲線
}
function saveLayout() {
const layout = {};
$('.node').each((_, el) => {
const $el = $(el);
layout[$el.data('id')] = { left: $el.position().left, top: $el.position().top };
});
localStorage.setItem('orgChartLayout', JSON.stringify(layout));
// 或 POST 到後端 API
}
function loadLayout() {
const layout = JSON.parse(localStorage.getItem('orgChartLayout') || '{}');
Object.entries(layout).forEach(([id, pos]) => {
$(`.node[data-id="${id}"]`).css(pos);
});
$('.node').each((_, el) => updateConnectors($(el))); // 重繪所有連線
}
此實作展示核心邏輯,生產環境建議採用成熟圖表庫(GoJS、JointJS、Mermaid)或圖編輯框架。