JS實現(xiàn)Select的option上下移動的方法
來源:易賢網(wǎng) 閱讀:1193 次 日期:2016-08-04 15:14:57
溫馨提示:易賢網(wǎng)小編為您整理了“JS實現(xiàn)Select的option上下移動的方法”,方便廣大網(wǎng)友查閱!

本文實例講述了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程序設(shè)計有所幫助。

更多信息請查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機網(wǎng)站地址:JS實現(xiàn)Select的option上下移動的方法
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 加入群交流 | 手機站點 | 投訴建議
工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號
聯(lián)系電話:0871-65317125(9:00—18:00) 獲取招聘考試信息及咨詢關(guān)注公眾號:hfpxwx
咨詢QQ:526150442(9:00—18:00)版權(quán)所有:易賢網(wǎng)