この記事では、ListBoxリストボックス内のアイテムの上下の動きを制御するJavaScriptの方法について説明します。参照のためにそれを共有してください。特定の分析は次のとおりです。
このJSコードは、ListBoxの要素を制御して上下に移動できます。これは非常に便利です。以下は詳細なコードです
コードコピーは次のとおりです。Functionlistbox_move(listId、direction){
var listbox = document.getElementById(listId);
var selindex = listbox.selectedIndex;
if(-1 == selindex){
アラート(「移動するオプションを選択してください。 ");
戻る;
}
var increment = -1;
if(direction == 'up')
増分= -1;
それ以外
Increment = 1;
if((selindex + increment)<0 ||
(selindex + increment)>(listbox.options.length-1)){
戻る;
}
var selvalue = listbox.options [selindex] .value;
var seltext = listbox.options [selindex] .text;
listbox.options [selindex] .value = listbox.options [selindex + increment] .value
listbox.options [selindex] .text = listbox.options [selindex + increment] .text
listbox.options [selindex + increment] .value = selvalue;
listbox.options [selindex + increment] .text = seltext;
listbox.selectedIndex = selindex + increment;
}
// ..
// ..
listbox_move( 'countrylist'、 'up'); //選択したオプションを上げます
listbox_move( 'countrylist'、 'down'); //選択したオプションを下に移動します
以下は、ブラウザで使用できる詳細なデモコードです
コードを次のようにコピーします。下のボタンをクリックして、選択ボックスからすべてのオプションを選択または解決しました。<br>
<選択id = "lsbox" name = "lsbox" size = "10"倍数= "">
<オプション値= "1">インド</option>
<オプション値= "2">米国</option>
<オプション値= "3">中国</option>
<オプション値= "4">イタリア</option>
<オプション値= "5">ドイツ</option>
<オプション値= "6">カナダ</option>
<オプション値= "7">フランス</option>
<オプション値= "8">英国</option>
</select> <br>
<button onclick = "listboxmove( 'lsbox'、 'up');">移動</button>
<button onclick = "listboxmove( 'lsbox'、 'down');">下に移動</button>
<スクリプト>
function listboxmove(listId、direction){
var listbox = document.getElementById(listId);
var selindex = listbox.selectedIndex;
if(-1 == selindex){
アラート(「移動するオプションを選択してください。 ");
戻る;
}
var increment = -1;
if(direction == 'up')
増分= -1;
それ以外
Increment = 1;
if((selindex + increment)<0 ||
(selindex + increment)>(listbox.options.length-1)){
戻る;
}
var selvalue = listbox.options [selindex] .value;
var seltext = listbox.options [selindex] .text;
listbox.options [selindex] .value = listbox.options [selindex + increment] .value
listbox.options [selindex] .text = listbox.options [selindex + increment] .text
listbox.options [selindex + increment] .value = selvalue;
listbox.options [selindex + increment] .text = seltext;
listbox.selectedIndex = selindex + increment;
}
</script>
この記事がみんなのJavaScriptプログラミングに役立つことを願っています。