HTML代码:(注意要用表格或CSS进行布局,下面代码用了表格进行布局)
<table>
<tr>
<td>关键词:</td>
<td><select name="sel" size="4" multiple class='multi'>
<option>程序员</option>
<option>C++</option>
<option>Java</option>
<option>JavaScript</option>
<option>深度学习</option>
<option>区块链</option>
<option>自然语言处理</option>
</select>
</td>
<td><input type="button" value=">" class='moveBtn' /><br>
<input type="button" value=">>" class='moveBtn' /><br>
<input type="button" value="<" class='moveBtn' /><br>
<input type="button" value="<<" class='moveBtn' /><br>
</td>
<td><select name="sel" size="4" multiple class='multi'></select>
</td>
</tr>
</table>
CSS代码:
select.multi{
width:100px;
height:100px;
margin:5px;
}
.moveBtn{
width:40px;
}
JavaScript代码:
window.onload= function (){
var moveBtns=document.getElementsByClassName('moveBtn');
moveBtns[0].addEventListener("click", function(){ moveSelected(true); });
moveBtns[1].addEventListener("click", function(){ moveAll(true); });
moveBtns[2].addEventListener("click", function(){ moveSelected(false); });
moveBtns[3].addEventListener("click", function(){ moveAll(false); });
//语法示例:element.addEventListener("click", myFunction);此时myFunction无法传递参数
//因为绑定的函数需传递参数,因此绑定一个“匿名函数”,在该“匿名函数”内调用指定函数
}
function moveSelected(flag){
var sel=document.getElementsByName('sel');
if(flag)
sel[1].appendChild(sel[0].options[sel[0].selectedIndex]);
else
sel[0].appendChild(sel[1].options[sel[1].selectedIndex]);
}
function moveAll(flag){
var sel=document.getElementsByName('sel');
var from=sel[0],to=sel[1];
if(!flag){
from=sel[1];
to=sel[0];
}
while(from.length>0)
to.appendChild(from.options[0]);
}