JavaScript 下拉框 左边添加至右边-LMLPHP

关于如何实现右边下拉框中选项的排序一时没有好的解决方法,等想到了回来补充

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="jquery-3.3.1.min.js"></script>
<style>
#select1 {
margin-left: 20px;
}
#select2{
margin-left: 20px;
}
span{
display: block;
border: 1px solid orange;
width: 135px;
background-color: coral;
color: whitesmoke;
box-shadow: 1px 1px 10.1px salmon;
margin-bottom: 5px;
margin-top: 5px;
cursor: pointer;
}
.container2{
position: absolute;
left:200px;
top: 8px;
}
</style>
</head>
<body>
<div class="container1">
<select multiple name="" id="select1" style="width:100px;height:150px;">
<!-- multiple:使下拉框能够同时拖选多个选项 -->
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<div>
<span id="add">选中添加到右边&gt;&gt;</span>
<span id="addAll">全部添加到右边&gt;&gt;</span>
</div>
</div>
<div class="container2">
<select multiple name="" id="select2" style="width:100px;height:150px;">
</select>
<div>
<span id="remove">选中删除到左边&lt;&lt;</span>
<span id="removeAll">全部删除到左边&lt;&lt;</span>
</div>
</div>
<script>
window.onload = function(){
var addBtn = document.getElementById("add");
var addAll = document.getElementById("addAll");
var container = document.getElementsByClassName("container1")[0];
var options = container.getElementsByTagName("option");
var select1 = document.getElementById("select1");
var select2 = document.getElementById("select2");
var optSore = [];
var valueStore = [];
console.log(options);
function addToRight(){
var i = 0;
for(i=0;i<options.length;i++){
if(options[i].selected){//别用.getAttrbute("selected")
// valueStore.push(options[i].value);
// optSore.push(options[i]);
console.log(options[i]);
var move = select1.removeChild(options[i]);
console.log(move);
select2.appendChild(move); i = i - 1;
//@解决了!options是左边容器中的选项列表,每次移除一个选项后,紧跟在后面的选项就会上移,
//所以要将这里的i前移一位 明天补个示意图
}
}
console.log(optSore,valueStore);
}
function addAllOpt(){
var i = 0;
for(i;i<options.length;i++){
optSore.push(options[i]);
valueStore.push(options[i].value);
}
console.log(optSore,valueStore);
} addBtn.addEventListener("click",addToRight,false);
addAll.addEventListener("click",addAllOpt,false);
}
</script>
<script>
// $(function(){
// $("#add").click(function(){
// var $selectedOpt = $("#select1 option:selected");
// var $remove = $selectedOpt.remove();//我惊了 你呢 原生js有这种操作吗
// $remove.prop("selected",false)//不然添加过去后会停留在被选中的状态
// .appendTo("#select2");
// });
// $("#addAll").click(function(){
// var $removeAll = $("#select1 option").remove();
// $removeAll.appendTo("#select2");
// })
// });
</script>
</body>
</html>
04-20 10:49