有些界面需要讓用戶自己調整項目的優先次序,比如自訂菜單順序、字段排列。實現思路是:取當前選中項的索引,與相鄰項交換 value 和 text,再把選中狀態移到新位置。
function listbox_move(listID, direction) {
var listbox = document.getElementById(listID);
var selIndex = listbox.selectedIndex;
if (-1 == selIndex) {
alert("Please select an option to move.");
return;
}
var increment = -1;
if (direction == 'up')
increment = -1;
else
increment = 1;
// 已經到達頭或尾,直接返回,避免越界
if ((selIndex + increment) < 0 ||
(selIndex + increment) > (listbox.options.length - 1)) {
return;
}
var selValue = listbox.options[selIndex].value;
var selText = listbox.options[selIndex].text;
listbox.options[selIndex].value = listbox.options[selIndex + increment].value;
listbox.options[selIndex].text = listbox.options[selIndex + increment].text;
listbox.options[selIndex + increment].value = selValue;
listbox.options[selIndex + increment].text = selText;
listbox.selectedIndex = selIndex + increment; // 讓選中框跟著走
}
// 調用
listbox_move('countryList', 'up'); // 上移
listbox_move('countryList', 'down'); // 下移
這裡有一個關鍵細節:交換完成後要重新設定 selectedIndex。少了這一句,項目雖然換了位置,但高亮會留在原處,用戶連點幾次就會覺得「越移越亂」。
Click below buttons to move the selected option up or down.<br>
<select id="lsbox" name="lsbox" size="10" 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><br>
<button onclick="listboxMove('lsbox','up')">Move Up</button>
<button onclick="listboxMove('lsbox','down')">Move Down</button>
<script>
function listboxMove(listID, direction) {
var listbox = document.getElementById(listID);
var selIndex = listbox.selectedIndex;
if (-1 == selIndex) {
alert("Please select an option to move.");
return;
}
var increment = -1;
if (direction == 'up') increment = -1; else increment = 1;
if ((selIndex + increment) < 0 ||
(selIndex + increment) > (listbox.options.length - 1)) {
return;
}
var selValue = listbox.options[selIndex].value;
var selText = listbox.options[selIndex].text;
listbox.options[selIndex].value = listbox.options[selIndex + increment].value;
listbox.options[selIndex].text = listbox.options[selIndex + increment].text;
listbox.options[selIndex + increment].value = selValue;
listbox.options[selIndex + increment].text = selText;
listbox.selectedIndex = selIndex + increment;
}
</script>
實務上如果列表較長,還可以配合拖拽(HTML5 Drag and Drop)來做排序;但對於十幾項以內的配置表單,這種「上移/下移」按鈕反而更精準、更好用。