选中下拉框中的选项实现左移右移
效果:
1. Html部分代码
<body><table align="center"> <tr> <td ><select size="15" id="left" > <option>左1</option> <option>左2</option> <option>左3</option> <option>左4</option> <option>左5</option> <option>左6</option> <option>左7</option> <option>左8</option> <option>左9</option> <option>左10</option> </select></td> <td> <input type="button" value="MoveRight" onclick="moveRight()"><br> <input type="button" value="MoveAllRight" onclick="moveAllright()"/><br> <input type="button" value="MoveLeft" onclick="moveLeft()"><br> <input type="button" value="MoveAllLeft" onclick="moveAllLeft()"><br> </td> <td> <select size="15" id="right"> <option>右1</option> <option>右2</option> <option>右3</option> <option>右4</option> <option>右5</option> <option>右6</option> <option>右7</option> </select> </td> <td></td> </tr> </table></body>
2. JavaScript脚本代码如下:
<script type="text/javascript"> function moveRight() { //获取左边select元素节点 var leftSelectNode = document.getElementById("left"); //获取子元素节点数组 //如果选定的索引号为-1,则提示用户 if (leftSelectNode.selectedIndex == -1) { alert("请选定需要移动的选项"); return; } //获取待移动的选项 var waitSelection = leftSelectNode.options[leftSelectNode.selectedIndex]; //获取右边的selec元素节点并加入 var rightSelectNode = document.getElementById("right"); //右边新增一个节点 rightSelectNode.appendChild(waitSelection); } function moveAllright() {//获取select对象 var leftSelectNode = document.getElementById("left"); var rightSelectNode = document.getElementById("right"); var optionsNodes = leftSelectNode.options; var length = optionsNodes.length; for (var i = 0; i < length; i++) { rightSelectNode.appendChild(optionsNodes[0]); } } function moveLeft() { //获取左边的select对象 var rightSelectNode = document.getElementById("right"); //没有选中则提示 if (rightSelectNode.selectedIndex == -1) { alert("请选择一个选项"); return; } //获取待移动的选项 var waitMoveNode = rightSelectNode.options[rightSelectNode.selectedIndex]; //获取左边的select对象 var leftSelectNode = document.getElementById("left"); //左边的select对象加入节点 leftSelectNode.appendChild(waitMoveNode); } function moveAllLeft() { //获取右边的select对象 var rightSelectNode = document.getElementById("right"); var leftSelectNode = document.getElementById("left"); var length = rightSelectNode.options.length; //遍历其option选项并加入到左边的select中 for (var i = 0; i < length; i++) { leftSelectNode.appendChild(rightSelectNode.options[0]); } } </script>
3.CSS简单代码如下:
<style> select, td { font:20px/40px '宋体'; } option {width: 100px; font:20px/40px '宋体'; } input { padding: 3px; font:20px/40px '宋体'; text-align: center; width: 130px; height: 40px; background-color: orange; } </style>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。