JavaScript键盘上下键的操作(选择)
两段使用键盘的上下键进行选择的代码:
第一段
程序代码
<Script Language="JScript">
function document.onkeydown(){
var rowsArray = document.all('oTable').rows;
for(var i=0;i<rowsArray.length;i++){
if(rowsArray[i].children[0].style.backgroundColor=='#dcdcdc'){
switch(window.event.keyCode){
case 38 :
if(i-1>=0){
rowsArray[i-1].children[0].style.backgroundColor = '#dcdcdc';
rowsArray[i].children[0].style.backgroundColor = '';
}
break;
case 40 :
if(i+1<=rowsArray.length-1){
rowsArray[i+1].children[0].style.backgroundColor = '#dcdcdc';
rowsArray[i].children[0].style.backgroundColor = '';
}
break;
}
break;
}
}
}
function document.onclick(){
if(window.event.srcElement.tagName!='TD'){ return; }
var rowsArray = document.all('oTable').rows;
for(var i=0;i<rowsArray.length;i++){
if(rowsArray[i].cells[0]==window.event.srcElement){
rowsArray[i].cells[0].style.backgroundColor = '#dcdcdc';
}else{
rowsArray[i].cells[0].style.backgroundColor = '';
}
}
}
</Script>
<style> TD { cursor: hand; } </style>
<table id="oTable" style="width:240px;border:1px highlight solid; font-size:12px;">
<tr>
<td style="background-color:#dcdcdc;">鼠标点击或按↑↓改变行的颜色</td>
</tr>
<tr>
<td>鼠标点击或按↑↓改变行的颜色</td>
</tr>
<tr>
<td>鼠标点击或按↑↓改变行的颜色</td>
</tr>
<tr>
<td>鼠标点击或按↑↓改变行的颜色</td>
</tr>
</table>
第二段
程序代码
<table id="tb">
<tr><td>00000000000000</td>
</tr>
<tr><td>11111111111111</td>
</tr>
<tr><td>22222222222222</td></tr>
<tr><td>33333333333333</td></tr>
</table>
<script>
var i=0;
function document.onkeydown(){
if (event.keyCode == 38){
for(var k=0;k<tb.rows.length;k++){
tb.rows(k).bgColor="";
}
tb.rows(--i%tb.rows.length).bgColor="#FF0000";
document.all.show.value=tb.rows(i%tb.rows.length).innerText;
}
if (event.keyCode== 40){
for(var k=0;k<tb.rows.length;k++){
tb.rows(k).bgColor="";
}
tb.rows(++i%tb.rows.length).bgColor="#FF0000";
document.all.show.value=tb.rows(i%tb.rows.length).innerText;
}
}
</script>
<input type="text" name="show">