本文實例講述了JS實現(xiàn)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數(shù)組;如是向下,得到自己到最后一個的option數(shù)組
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程序設計有所幫助。