萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實作權限選擇雙向移動選單(Shuttle/雙欄選單)

權限管理、角色配置、標籤選擇等場景常需「雙欄選單」:左側可用項目、右側已選項目,支援單項/全量雙向移動。本文提供原生 DOM 完整實作,包含多選移動(> / <)、全量移動(>> / <<)、選項順序保持、多重選取支援。

介面結構

<select id="select1" multiple="multiple" style="float:left;width:100px;height:200px;">
    <option>新增</option>
    <option>刪除</option>
    <option>修改</option>
    <option>儲存</option>
    <option>查詢</option>
</select>

<div style="float:left;width:50px; text-align:center; padding-top:50px;">
    <input type="button" value=">" onclick="selectToRight()" title="移動選中項目到右側" /><br/>
    <input type="button" value="<" onclick="selectToLeft()" title="移動選中項目到左側" /><br/>
    <input type="button" value=">>" onclick="selectToRightAll()" title="全部移動到右側" /><br/>
    <input type="button" value="<<" onclick="selectToLeftAll()" title="全部移動到左側" />
</div>

<select id="select2" multiple="multiple" style="float:left;width:100px;height:200px;"></select>

核心邏輯:多選移動(保持選項順序)

關鍵技巧:**反向迴圈** 遍歷 childNodes,避免移除元素導致索引錯亂。

function moveSelected(sourceSelect, targetSelect) {
    // 反向迴圈:從最後一個 option 開始檢查
    for (var i = sourceSelect.childNodes.length - 1; i >= 0; i--) {
        var option = sourceSelect.childNodes[i];
        // childNodes 包含文字節點,需過濾
        if (option.tagName === 'OPTION' && option.selected) {
            sourceSelect.removeChild(option);
            option.selected = false; // 移動後取消選中
            targetSelect.appendChild(option); // 附加到目標末尾,保持相對順序
        }
    }
}

function selectToRight() {
    moveSelected(document.getElementById("select1"), document.getElementById("select2"));
}

function selectToLeft() {
    moveSelected(document.getElementById("select2"), document.getElementById("select1"));
}

核心邏輯:全量移動

使用 getElementsByTagName('option') 取得即時集合,**固定取第 0 項** 移動,直到來源清空。

function moveAll(sourceSelect, targetSelect) {
    var options = sourceSelect.getElementsByTagName("option");
    var count = options.length; // 必須先存長度,因 appendChild 會減少集合長度
    
    for (var i = 0; i < count; i++) {
        var option = options[0]; // 永遠取第一個(因為會被移除)
        targetSelect.appendChild(option);
    }
    // 保險清空
    sourceSelect.options.length = 0;
}

function selectToRightAll() {
    moveAll(document.getElementById("select1"), document.getElementById("select2"));
}

function selectToLeftAll() {
    moveAll(document.getElementById("select2"), document.getElementById("select1"));
}

關鍵技巧總結

技巧說明
反向迴圈移除for (i = len-1; i >= 0; i--) 避免移除元素導致後續索引偏移
childNodes vs optionschildNodes 含文字節點需檢查 tagName;options 集合僅含 <option> 更乾淨
固定取 options[0]全量移動時,每次移除第一項,集合自動縮減,迴圈固定次數即可清空
selected = false移動後重置選中狀態,避免視覺殘留
appendChild 移動節點DOM 節點移動而非複製,保持事件綁定、引用完整

現代化重構:資料驅動 + 單向資料流

現代框架(Vue/React)建議以「資料陣列」為單一真相來源,UI 衍生渲染:

// Vue 3 Composition API 範例
import { ref, computed } from 'vue';

const allPermissions = ['新增', '刪除', '修改', '儲存', '查詢'];
const selected = ref([]);

const available = computed(() => 
    allPermissions.filter(p => !selected.value.includes(p))
);

function moveRight(perms) {
    perms.forEach(p => { if (!selected.value.includes(p)) selected.value.push(p); });
}

function moveLeft(perms) {
    perms.forEach(p => { selected.value = selected.value.filter(s => s !== p); });
}

function moveAllRight() { selected.value = [...allPermissions]; }
function moveAllLeft() { selected.value = []; }

UX 改進建議

  • 雙擊移動:ondblclick 直接移動單項
  • 排序功能:右側支援上下移動調整優先序
  • 搜尋過濾:選項超過 20 個時必備
  • 鍵盤支援:Enter/Space 移動、方向鍵導航、Home/End 跳首尾
  • 無障礙:role="listbox"、aria-multiselectable、aria-label

成熟開源替代方案

  • vanilla-select:零依賴、輕量、可訪問性佳
  • dual-listbox:功能完整、支援分組、搜尋、排序
  • Element Plus / Ant Design / Vuetify 內建 Transfer / TransferPanel 元件
copyright © 萬盛學電腦網 all rights reserved