HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>移动option</title>
<style type="text/css">
select {
width: 200px;
}
?
.box {
float: left;
}
</style>
</head>
<body>
<div class="box">
<select size="8" id="left-select">
<option value="">1</option>
<option value="">2</option>
<option value="">3</option>
<option value="">4</option>
<option value="">5</option>
<option value="">6</option>
<option value="">7</option>
<option value="">8</option>
</select>
<br>
<button id="left_up">向上移动</button>
<button>向下移动</button>
<button id="right">向右移动</button>
<button id="right_all">全部右移</button>
</div>
<div class="box">
<select size="8" id="right-select">
<option value="">1</option>
<option value="">2</option>
<option value="">3</option>
<option value="">4</option>
<option value="">5</option>
<option value="">6</option>
<option value="">7</option>
<option value="">8</option>
</select>
<br>
<button>向上移动</button>
<button>向下移动</button>
<button>向左移动</button>
<button>全部左移</button>
</div>
<script src="./js/移动option.js"></script>
</body>
</html>
javascript
(function() {
var leftSelect = document.getElementById(‘left-select‘);
var rightSelect = document.getElementById(‘right-select‘);
var leftUpBtn = document.getElementById(‘left_up‘);
var rightBtn = document.getElementById(‘right‘);
var rightAllBtn = document.getElementById(‘right_all‘);
?
leftUpBtn.onclick = function() {
var index = leftSelect.selectedIndex;
// 如果在select中没有选中option,那么不会进行后续的操作
if(index !== -1) {
var option = leftSelect.options[index];
?
if(index === 0) {
leftSelect.appendChild(option);
} else {
leftSelect.insertBefore(option, leftSelect.options[index - 1]);
}
}
};
?
rightBtn.onclick = function() {
var index = leftSelect.selectedIndex;
if(index !== -1) {
var option = leftSelect.options[index];
?
rightSelect.appendChild(option);
}
};
?
rightAllBtn.onclick = function() {
for(var i = 0; i < leftSelect.options.length;) {
rightSelect.appendChild(leftSelect.options[i]);
}
};
})();
时间: 2024-10-26 07:52:00