DOM应用案例--列表框移动

来源:互联网 发布:淘宝客软文编辑器 编辑:程序博客网 时间:2024/06/06 04:30

简述:有两侧列表框,将左侧的列表框移动右侧列表框,有:双击右移、批量右移、全部右移。如图:



代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8"></head><body><div><select style="width:60px" multiple size="10" id="leftID"><option>选项A</option><option>选项B</option><option>选项C</option><option>选项D</option><option>选项E</option><option>选项F</option><option>选项G</option><option>选项H</option><option>选项I</option><option>选项J</option></select></div><div style="position:absolute;left:100px;top:60px"><input type="button" value="批量右移" id="rightMoveID" /></div><div style="position:absolute;left:100px;top:90px"><input type="button" value="全部右移" id="rightMoveAllID" /></div><div style="position:absolute;left:220px;top:20px"><select multiple size="10" style="width:60px" id="rightID"></select></div></body><script type="text/javascript">//双击右移document.getElementById("leftID").ondblclick = function(){//定位左边选中的option的元素节点var optionElement = this[this.selectedIndex];//将其添加到右边选择框document.getElementById("rightID").appendChild(optionElement);};//全部右移document.getElementById("rightMoveAllID").onclick = function(){//定位左侧选择框中的option元素var options = document.getElementById("leftID").options;/**因为当option移动的时候,option.length是动态改变的,每移动一个,*options.length就自动减一,所以如果使用在for循环里直接使用options.length时,*当i增加到5时,options.length也减少到5,所以此时循环终止,结果只移动了5个,*所以必须将option的数量预先用size存起来。*可将其想象成栈,弹出一个,下面的自动向上移动一位,就像弹夹那样*/var size = options.length;//循环将左侧的option元素添加到右侧for(var i=0; i<size; i++){document.getElementById("rightID").appendChild(options[0]);}};//批量右移document.getElementById("rightMoveID").onclick = function() {//定位左边select对象var selectElement = document.getElementById("leftID");//取得option对象组成的集合var optionSelectArray = selectElement.options;var size = optionSelectArray.length;//注意这里的size是动态改变的//如果这里的size写成optionSelectArray.length,选中10个,只有5个会右移过去,for ( var i = 0; i < size; i++) {//获取到选中的option对象var optionElement = selectElement[selectElement.selectedIndex];//删除左边选中的节点selectElement.removeChild(optionElement);//将选中的节点,添加到右侧中document.getElementById("rightID").appendChild(optionElement);}};</script></html>