代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>选择水果</title>
</head>
<body>
<select size="7" style="width: 150px;height: 200px;" multiple="multiple" id="all">
<option>苹果</option>
<option>橘子</option>
<option>香蕉</option>
<option>橙子</option>
<option>草莓</option>
</select>
<input type="button" value=">>" id="btn1">
<input type="button" value="<<" id="btn2">
<input type="button" value=">" id="btn3">
<input type="button" value="<" id="btn4">
<select size="7" style="width: 150px;height: 200px;" multiple="multiple" id="sel">
</select>
</body>
</html>
<script>
var all=document.getElementById("all");
var sel=document.getElementById("sel");
var btn1=document.getElementById("btn1");
var btn2=document.getElementById("btn2");
var btn3=document.getElementById("btn3");
var btn4=document.getElementById("btn4");
btn1.onclick=function(){
//for循环条件不能为for (var i = all.children.length; i >0; i--) ???????
var len=all.children.length;
for (var i=0; i<len; i++) {
var option=all.children[0];
//去掉select元素的选中效果
option.selected=false;
sel.appendChild(option);
}
}
btn2.onclick=function(){
//for循环条件不能为for (var i = all.children.length; i >0; i--) ???????
//水果的顺序发生变化
// for (var i = sel.children.length-1; i >=0; i--) {
// var option1=sel.children[i];
// all.appendChild(option1);
// }
var len=sel.children.length;
for (var i=0; i<len; i++) {
var option=sel.children[0];
//去掉select元素的选中效果
option.selected=false;
all.appendChild(option);
}
}
//移动选中的水果
btn3.onclick=function(){
var array=[];
for (var i=0; i<all.children.length; i++){
var option=all.children[i];
if (option.selected) {
array.push(option);
//去掉select元素的选中效果
option.selected=false;
}
}
//把数组中的元素移动到另一边
for (var i = 0; i < array.length; i++) {
var arr=array[i];
sel.appendChild(arr);
}
}
btn4.onclick=function(){
var array=[];
for (var i = 0; i < sel.length; i++) {
var option=sel.children[i];
if (option.selected) {
array.push(option);
//去掉select元素的选中效果
option.selected=false;
}
}
for (var i = 0; i < array.length; i++) {
var arr=array[i];
all.appendChild(arr);
}
}
</script>
运行结果如下