操作select选中项,上下移动,原理很简单,就是根据当前选中项的索引加1或者减1,得到上一个或者下一个的索引值,然后在通过insertBefore方法,用新的项替换原来的项
Code
function moveOption(obj)
{
var oListbox=document.getElementById("oListbox");
if(oListbox==null)
{
return;
}
if(oListbox.selectedIndex<0)
{
//没选
alert("请选择要移动的项");
return;
}
var op=oListbox.options[oListbox.selectedIndex];//当前选中的项
var downOp;
if(obj=="up")
{
if(oListbox.selectedIndex==0)
{
alert("已经是第一个");
return;
}
downOp=oListbox.options[oListbox.selectedIndex-1];
oListbox.insertBefore(op,downOp);
}
else if(obj=="down")
{
if(oListbox.selectedIndex==oListbox.options.length-1)
{
alert("已经是最后一个");
return;
}
downOp=oListbox.options[oListbox.selectedIndex+1];
oListbox.insertBefore(downOp,op);
}
}
Code
<select id="oListbox" multiple="multiple" style="width:200px;height:100px;">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select><br>
<input type="button" value="向上" onclick="moveOption('up')"><input type="button" value="向下" onclick="moveOption('down')">