本文实例讲述了JS实现Select的option上下移动的方法。分享给大家供大家参考,具体如下:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function UpOrDown(direct, selectId) {//direct : 1:Up, -1:Down
var obj = document.getElementById(selectId);
var len = obj.length;
var index = obj.selectedIndex;
//如果:1.没有选中的项; 2.向上,但已是最上; 3.向下,但是最下,不作处理
if ( (index == -1) || (direct == -1 && index == 0) || (direct == 1 && index >= len - 1) )
return;
var swapIndex = index + direct;
var tempOptions = new Array();
for (var i = 0; i < len; i++){
tempOptions[tempOptions.length] = obj.options[i == index?swapIndex:(i == swapIndex?index:i)];
}
obj.options.length = 0;
for (var i = 0; i < len; i++)
obj.options.add(tempOptions[i]);
}
function UpOrDown2(direct, selectId) {//direct : 1:Up, 0:Down
var obj = document.getElementById(selectId);
var len = obj.length;
var index = obj.selectedIndex;
//如果:1.没有选中的项; 2.向上,但已是最上; 3.向下,但是最下,不作处理
if( (index == -1) || (direct == 1 && index == 0) || (direct == 0 && index >= len - 1) )
return;
var tempOptions = new Array();
//如是向上,得到自己上一个到最后的option数组;如是向下,得到自己到最后一个的option数组
for (var i = index - direct; i < len; i++)
tempOptions[tempOptions.length] = obj.options[i];
//去除刚才取得的部分
obj.options.length = index - direct;
//颠倒取两个option
obj.options.add(tempOptions[1]);
obj.options.add(tempOptions[0]);
//将余下的option全部加进来
for (var i = 2; i < tempOptions.length; i++)
obj.options.add(tempOptions[i]);
}
</script>
</head>
<body>
<table>
<tr>
<td>
<select id="Select1" size="100" style="width:100px;height:200px;">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</td>
<td>
<img id="imgUp" alt="Up" onclick="UpOrDown(-1,'Select1')" style="cursor:pointer;" /><br />
<img id="imgDown" alt="Down" onclick="UpOrDown(1,'Select1')" style="cursor:pointer;" />
</td>
<td>
<img id="img1" alt="Up2" onclick="UpOrDown2(1,'Select1')" style="cursor:pointer;" /><br />
<img id="img2" alt="Down2" onclick="UpOrDown2(0,'Select1')" style="cursor:pointer;" />
</td>
</tr>
</table>
</body>
</html>
希望本文所述对大家JavaScript程序设计有所帮助。