水果选择排序版本
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
select {
width: 150px;
height: 200px;
background-color: #7bff68;
}
</style>
</head>
<body>
<select size="10" name="aaa" id="sel1" multiple="multiple">
<option value="0">1香蕉</option>
<option value="1">2苹果</option>
<option value="2">3大鸭梨</option>
<option value="3">4草莓</option>
</select>
<input type="button" value=">>>"/>
<input type="button" value="<<<"/>
<input type="button" value=">"/>
<input type="button" value="<"/>
<select size="10" name="bbb" id="sel2" multiple="multiple">
</select>
</body>
</html>
原始版本
<script>
var sel1 = document.getElementById("sel1");
var sel2 = document.getElementById("sel2");
var inpArr = document.getElementsByTagName("input");
inpArr[0].onclick = function(){
var optArr = sel1.children;
for(var i = 0;i<optArr.length;){
sel2.appendChild(optArr[i]);
}
}
inpArr[1].onclick = function(){
var optArr = sel2.children;
for(var i = 0;i<optArr.length;){
sel1.appendChild(optArr[i]);
}
}
inpArr[2].onclick = function(){
var optArr = sel1.children;
for(var i=optArr.length-1;i>=0;i--){
if(optArr[i].selected == true){
optArr[i].selected = false;
sel2.appendChild(optArr[i]);
}
}
var aaa = Array.from(sel2.children).sort(function(a,b){
return a.value - b.value;
});
for(var i =0;i<sel2.children.length;i++){
sel2.removeChild(sel2.children[i]);
}
for (var i = 0; i < aaa.length; i++) {
sel2.appendChild(aaa[i]);
}
}
inpArr[3].onclick = function(){
var optArr = sel2.children;
for(var i = optArr.length - 1;i>=0;i--){
if(optArr[i].selected == true){
optArr[i].selected = false;
sel1.appendChild(optArr[i]);
}
}
var bbb = Array.from(sel1.children).sort(function(a,b){
return a.value - b.value;
});
for(var i = 0;i<sel1.children.length;i++){
sel1.removeChild(sel1.children[i]);
}
for(var i = 0;i<bbb.length;i++){
sel1.appendChild(bbb[i]);
}
}
</script>
封装版本
<script>
var sel1 = document.getElementById("sel1");
var sel2 = document.getElementById("sel2");
var inpArr = document.getElementsByTagName("input");
inpArr[0].onclick = function(){
fn1(sel1,sel2);
}
inpArr[1].onclick = function(){
fn1(sel2,sel1);
}
inpArr[2].onclick = function(){
fn2(sel1,sel2);
}
inpArr[3].onclick = function(){
fn2(sel2,sel1);
}
function fn1(ele1,ele2){
var arr = ele1.children;
for(var i = arr.length - 1;i>=0;i--){
ele2.appendChild(arr[0]);
}
}
function fn2(ele1,ele2){
var arr = ele1.children;
for(var i = arr.length - 1;i>=0;i--){
if(arr[i].selected == true){
arr[i].selected = false;
ele2.appendChild(arr[i]);
}
}
var arr1 = Array.from(ele2.children).sort(function(a,b){
return a.value - b.value;
});
for(var i =0 ;i<ele2.children.length;i++){
ele2.removeChild(ele2.children[i]);
}
for(var i = 0;i<arr1.length;i++){
ele2.appendChild(arr1[i]);
}
}
</script>