<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>元素移动案例</title>
<style>
#main {
width: 500px;
margin: auto;
}
select {
width: 130px;
height: 260px;
text-align: center;
}
button {
width: 130px;
height: 36px;
background-color: #2faf2f;
margin: 9px 0;
border-radius: 5px;
}
#left {
float: left;
}
#right {
margin-left: 20px;
float: left;
}
</style>
<script>
//1.(单/多)左边->右边
function selectLeft() {
var selectLeft = document.getElementById("selectToLeft");
var selectRight = document.getElementById("selectToRight");
var options = selectLeft.getElementsByTagName("option");
for (let i = 0; i < options.length; i++) {
if (options[i].selected == true) {
selectRight.appendChild(options[i])
i--
}
}
}
//2.(全部)左边->右边
function allLeft() {
var selectLeft = document.getElementById("selectToLeft");
var selectRight = document.getElementById("selectToRight");
var options = selectLeft.getElementsByTagName("option");
for (let i = 0; i < options.length; i++) {
selectRight.appendChild(options[i])
i--
}
}
//3.(单/多)右边->左边
function selectRight() {
var selectLeft = document.getElementById("selectToLeft");
var selectRight = document.getElementById("selectToRight");
var options = selectRight.getElementsByTagName("option");
for (let i = 0; i < options.length; i++) {
if (options[i].selected == true) {
selectLeft.appendChild(options[i])
i--
}
}
}
//4.(全部)右边->左边
function allRight() {
var selectLeft = document.getElementById("selectToLeft");
var selectRight = document.getElementById("selectToRight");
var options = selectRight.getElementsByTagName("option");
for (let i = 0; i < options.length; i++) {
selectLeft.appendChild(options[i])
i--
}
}
</script>
</head>
<body>
<div id="main">
<div id="left">
<select id="selectToLeft" multiple="multiple">
<option>JavaSE</option>
<option>JavaWeb</option>
<option>MySQL</option>
<option>JDBC</option>
</select>
<div>
<button type="button" onclick="selectLeft()">(单/多)左边->右边</button><br/>
<button type="button" onclick="allLeft()">(全部)左边->右边</button>
</div>
</div>
<div id="right">
<div>
<select id="selectToRight" multiple="multiple">
<option>HTML</option>
<option>CSS</option>
</select>
</div>
<div>
<button type="button" onclick="selectRight()">(单/多)右边->左边</button><br/>
<button type="button" onclick="allRight()">(全部)右边->左边</button>
</div>
</div>
</div>
</body>
</html>