The example in this article describes the method of moving up and down the Select option using JS. Share it with everyone for your reference, the details are as follows:
<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>
Readers who are interested in more JavaScript-related content can check out the special topics on this site: "Summary of JavaScript search algorithm techniques", "Summary of JavaScript animation special effects and techniques", "Summary of JavaScript errors and debugging techniques", "Summary of JavaScript data structures and algorithm techniques", "Summary of JavaScript traversal algorithms and techniques" and "JavaScript Mathematics Summary of operation usage》
I hope this article will be helpful to everyone in JavaScript programming.