1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>下拉列表左右选择</title> 6 <style type="text/css"> 7 div { 8 width: 200px; 9 float: left; 10 } 11 select { 12 width: 100px; 13 height: 180px; 14 padding: 10px; 15 } 16 </style> 17 </head> 18 <body> 19 <div> 20 <select multiple="multiple" id="leftSel" style="margin-left: 17px;"> 21 <option>选项1</option> 22 <option>选项2</option> 23 <option>选项3</option> 24 <option>选项4</option> 25 <option>选项5</option> 26 <option>选项6</option> 27 <option>选项7</option> 28 <option>选项8</option> 29 <option>选项9</option> 30 <option>选项10</option> 31 </select> 32 <br /> 33 <input type="button" value="选中添加到右边 ->" onclick="choiceToRight()"> 34 <br /> 35 <input type="button" value="全部添加到右边 -->" onclick="allToRight()"> 36 </div> 37 38 <div> 39 <select multiple="multiple" id="rightSel" style="margin-left: 17px;"></select> 40 <br /> 41 <input type="button" value="<- 选中添加到左边" onclick="choiceToLeft()"> 42 <br /> 43 <input type="button" value="<-- 全部添加到左边" onclick="allToLeft()"> 44 </div> 45 46 <script type="text/javascript"> 47 // 获取select 48 var leftSel = document.getElementById("leftSel"); 49 var rightSel = document.getElementById("rightSel"); 50 // 选中添加到右边 51 function choiceToRight() { 52 toSel(leftSel, rightSel, true); 53 } 54 // 全部添加到右边 55 function allToRight() { 56 toSel(leftSel, rightSel, false); 57 } 58 // 选中添加到左边 59 function choiceToLeft() { 60 toSel(rightSel, leftSel, true); 61 } 62 // 全部添加到左边 63 function allToLeft() { 64 toSel(rightSel, leftSel, false); 65 } 66 // 如果flag为true,就是选中添加,如果为false,就是全部添加 67 function toSel(fromSel, toSel, flag) { 68 var subSel = fromSel.getElementsByTagName("option"); 69 if (flag) { 70 for (var i = 0; i < subSel.length; i++) { 71 if (subSel[i].selected) { 72 toSel.appendChild(subSel[i]); 73 // 因为subSel的length每次会-1,所以让i归零,保证每次for循环都能被执行到 74 i--; 75 } 76 } 77 } else { 78 for (var i = 0; i < subSel.length; i++) { 79 toSel.appendChild(subSel[i]); 80 i--; 81 } 82 } 83 } 84 </script> 85 </body> 86 </html>