萬盛學電腦網

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

JavaScript 實現列表框選項上下移動:排序交互完整實現

核心邏輯

選中某項後,點擊「上移」/「下移」按鈕,與相鄰項交換 value 与 text,並同步更新 selectedIndex 保持選中狀態跟隨。

通用移動函數

/**
 * 列表框選項上下移動
 * @param {string} listId - select 元素 id
 * @param {string} direction - 'up' | 'down'
 */
function moveOption(listId, direction) {
  var list = document.getElementById(listId);
  var idx = list.selectedIndex;
  
  // 未選中或已在邊界
  if (idx === -1) return alert('請先選中一項');
  if (direction === 'up' && idx === 0) return;
  if (direction === 'down' && idx === list.options.length - 1) return;
  
  var targetIdx = direction === 'up' ? idx - 1 : idx + 1;
  
  // 交換 value 和 text(保留 selected/defaultSelected 等屬性不變)
  var curOpt = list.options[idx];
  var tarOpt = list.options[targetIdx];
  
  var tempVal = curOpt.value;
  var tempText = curOpt.text;
  
  curOpt.value = tarOpt.value;
  curOpt.text  = tarOpt.text;
  tarOpt.value = tempVal;
  tarOpt.text  = tempText;
  
  // 選中狀態跟隨移動
  list.selectedIndex = targetIdx;
}

完整可運行示例

<!DOCTYPE html>
<html><head><meta charset="utf-8"><style>
#listBox { width:200px; height:180px; }
.btns button { display:block; margin:5px 0; width:60px; }
</style></head><body>

<select id="listBox" multiple>
  <option value="1">India</option>
  <option value="2">United States</option>
  <option value="3">China</option>
  <option value="4">Italy</option>
  <option value="5">Germany</option>
  <option value="6">Canada</option>
  <option value="7">France</option>
  <option value="8">United Kingdom</option>
</select>

<div class="btns">
  <button onclick="moveOption('listBox', 'up')">上移</button>
  <button onclick="moveOption('listBox', 'down')">下移</button>
</div>

<script>
// 上方 moveOption 函數代碼
</script>
</body></html>

進階:支援多選項批量移動

function moveMultiOptions(listId, direction) {
  var list = document.getElementById(listId);
  var selected = Array.from(list.selectedOptions) // 獲取所有選中項
    .map(opt => opt.index)                        // 獲取索引
    .sort((a, b) => direction === 'up' ? a - b : b - a); // 上移升序、下移降序
  
  if (!selected.length) return;
  
  // 檢查邊界:最頂項不能上移,最底項不能下移
  var blocked = direction === 'up' ? selected.some(i => i === 0)
                                   : selected.some(i => i === list.options.length - 1);
  if (blocked) return;
  
  // 執行交換(逆序處理避免索引偏移)
  selected.forEach(function(idx) {
    var targetIdx = direction === 'up' ? idx - 1 : idx + 1;
    swapOptions(list, idx, targetIdx);
  });
  
  // 重新選中移動後的項(索引已變)
  // 簡單處理:清空選中,按新索引重選
  // 實際項目建議維護 value 集合重新匹配
}

function swapOptions(list, i, j) {
  var o1 = list.options[i], o2 = list.options[j];
  var v = o1.value, t = o1.text;
  o1.value = o2.value; o1.text = o2.text;
  o2.value = v; o2.text = t;
}

現代框架對比

框架實現方式核心 API
Vue 2/3操作數組 splice/sortv-for 自動響應
Reactstate 數組 toSorted/with (ES2023)setState 觸發重渲染
原生 JS直接操作 options 集合add/remove/swap

總結

原生 select 選項移動的核心是 交換 value/text 屬性 而非移動 Option 節點本身(避免 IE 兼容性問題)。單選場景代碼極簡,多選批量移動需注意索引偏移與邊界檢查。現代開發中,若非維護舊系統,建議優先使用框架的數據驅動模式,將排序邏輯放入數組操作層,僅在極簡頁面或無框架環境下使用本文方案。

copyright © 萬盛學電腦網 all rights reserved