在做项目的时候需要这个功能,在网上找了也没找到合适的,于是就自己写了个。
把核心代码提取出来,希望对大家有帮助。
<script language="javascript">
<!--
function move(sel, selIndex1, selIndex2)
{
var selValue, selText;
selValue = sel.options[selIndex1].value;
selText = sel.options[selIndex1].innerText;
sel.options[selIndex1].value = sel.options[selIndex2].value;
sel.options[selIndex1].innerText = sel.options[selIndex2].innerText;
sel.options[selIndex2].value = selValue;
sel.options[selIndex2].innerText = selText;
}
function doMove(sel, action)
{
var i, selIndexs = "", selArray;
if((sel.selectedIndex == -1) || (action == "u" && sel.options[0].selected) || (action == "d" && sel.options[sel.length-1].selected))
return;
if(action == "u") {
for(i = 0; i < sel.length; i++)
if(sel.options[i].selected) {
sel.options[i].selected = false;
selIndexs += (i - 1) + ",";
move(sel, i, i - 1);
}
} else {
for(i = sel.length-1; i >= 0; i--)
if(sel.options[i].selected) {
sel.options[i].selected = false;
selIndexs += (i + 1) + ",";
move(sel, i + 1, i);
}
}
selArray = selIndexs.split(",");
for(i=0;i<selArray.length-1;i++)
sel.options[selArray[i]].selected = true;
}-->
</script>
示例:
<form name="f" method="post">
<select id="sel" name="s" size="10" multiple="multiple" style="width:130px;">
<option value="1">select1</option>
<option value="2">select2</option>
<option value="3">select3</option>
<option value="4">select4</option>
<option value="5">select5</option>
<option value="6">select6</option>
<option value="7">select7</option>
<option value="8">select8</option>
<option value="9">select9</option>
</select>
<BR>
<input type="button" value="Up" onclick="doMove(this.form.s,'u')" />
<input type="button" value="Down" onclick="doMove(this.form.s,'d')" />
</form>
演示(按住Ctrl可多选):