<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
select {
width: 200px;
height: 200px;
background-color: blue;
}
</style>
<script>
window.onload = function () {
var all = document.getElementById('all');
var select = document.getElementById('select');
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
var btn3 = document.getElementById('btn3');
var btn4 = document.getElementById('btn4');
// 全选
btn1.onclick = function () {
// 先获取子元素个数 将来再发生变化不会受到影响
//现在len的值始终是当前获取到的all.children.length 当前个数为5
var len = all.children.length;
for (var i=0; i < len; i++) {
var option = all.children[0];
option.selected = false;
select.appendChild(option);
}
// 使用这种方式移动子元素的话 如果子元素有时间 移动后元素的事件消失
select.innerHTML = all.innerHTML;
// 如果子元素有事件 此时会发生内存泄漏(该释放的对象内存没有被释放)
all.innerHTML = ''; // 清空子元素
}
// 反选
btn2.onclick = function () {
var len = select.children.length;
for (var i=0; i < len; i++) {
var option = select.children[0];
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);
// 去掉当前的option的选中状态
option.selected = false;
}
}
// 把数组中的option移动到第二个select中
for (var j=0; j < array.length; j++) {
select.appendChild(array[j]);
}
}
// 移动选中的水果
btn4.onclick = function () {
// 存储所有被选中的水果
var array = [];
for (var i=0; i < select.children.length; i++) {
var option = select.children[i];
if (option.selected) {
array.push(option);
// 去掉当前的option的选中状态
option.selected = false;
}
}
// 把数组中的option移动到第二个select中
for (var j=0; j < array.length; j++) {
all.appendChild(array[j]);
}
}
}
</script>
</head>
<body>
<select name="" multiple="multiple" id="all">
<option value="">苹果</option>
<option value="">西瓜</option>
<option value="">猴蜜桃</option>
<option value="">菠萝</option>
<option value="">草莓</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 name="" multiple="multiple" id="select"></select>
</body>
</html>