JavaScript实现ListBox左右移动与上下排序功能示例

作者:交互手记

时间:2026-10-27

浏览:294

本文提供基于JavaScript的ListBox控件交互实现方案,涵盖左右双向移动选项与上下排序功能。代码包含HTML表单结构及JS函数逻辑,支持双击或按钮点击触发移动,并实现选中项的上下位置交换。适用于IE6及FireFox1.5等旧版浏览器环境,需注意swapOptionProperties函数中值交换逻辑可能存在笔误。

具体实现代码如下所示:

HTML结构与交互界面<html>
<head>
<meta http-equiv="Content-Type " content="text/html; charset=gb2312 ">
<title>list测试</title>
</head>
<body>
<div style="font-size: 10pt;">
注1:支持通过左右按钮移动选项进行选取
<br />
<br />
注:本页面仅在IE6/FireFox1.5下测试过。其它浏览器或其它版本未经测试。
<br />
<hr />
</div>
<form name="frm">
<table>
<tr>
<td>
<select name="SrcSelect" size="6" style="font-size: 11pt; width: 160px; height: 160px"
multiple="multiple" ondblclick="moveLeftOrRight(document.frm.SrcSelect,document.frm.ObjSelect) ">
<option value="1">讲师</option>
</select>
</td>
<td width="30px">
<input align="left" type="button" value="> " onclick="moveLeftOrRight(document.frm.SrcSelect,document.frm.ObjSelect) ">
<br>
<br>
<input align="left" type="button" value=" < " onclick="moveLeftOrRight(document.frm.ObjSelect,document.frm.SrcSelect) ">
</td>
<td>
<select name="ObjSelect" size="6" style="font-size: 11pt; width: 160px; height: 160px"
multiple="multiple" ondblclick="moveLeftOrRight(document.frm.ObjSelect,document.frm.ObjSelect) ">
<option value="2">教学管理员</option>
<option value="3">超级管理员</option>
</select>
</td>
</tr>
</table>
</form>
</body>
JavaScript核心逻辑实现<script type="text/javascript" language="javascript">
//上移
function moveUp() {
var theObjOptions = document.frm.ObjSelect.options;
for (var i = 1; i < theObjOptions.length; i++) {
if (theObjOptions[i].selected && !theObjOptions[i - 1].selected) {
swapOptionProperties(theObjOptions[i], theObjOptions[i - 1]);
            }
        }
    }
//下移
 function moveDown() {
 var theObjOptions = document.frm.ObjSelect.options;
 for (var i = theObjOptions.length - 2; i > -1; i--) {
 if (theObjOptions[i].selected && !theObjOptions[i + 1].selected) {
 swapOptionProperties(theObjOptions[i], theObjOptions[i + 1]);
 }
 }
 }
function swapOptionProperties(option1, option2) {
 var tempStr = option1.value;
 option1.value = option2.value;
 option1.value = tempStr;
 tempStr = option1.text;
 option1.text = option2.text;
 option2.text = tempStr;
 tempStr = option1.selected;
 option1.selected = option2.selected;
 option2.selected = tempStr;
 }
//列表框的位置移动
 function moveLeftOrRight(fromObj, toObj) {
 for (var i = 0; i < fromObj.length; i++) {
 var srcOption = fromObj.options[i];
 if (srcOption.selected) {
 toObj.appendChild(srcOption);
 i--;
 }
 }
 }
</script>

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章