js源码--键盘控制

本文介绍了一种使用JavaScript实现的表格元素键盘导航脚本。该脚本通过监听键盘事件来帮助用户在表格内的不同单元格间进行快速切换。具体来说,当用户按下左箭头键时,焦点会移动到当前单元格左边的单元格;按下右箭头键时,焦点则移动到右边的单元格;上下箭头键则使焦点在行之间切换。
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<script>
document.onkeydown=keydown;
function keydown(){
obj=window.event.srcElement
objId=window.event.srcElement.id
    if(objId.indexOf("t")!=-1){
        if(window.event.keyCode==37){
        var s=document.selection.createRange();
        s.setEndPoint("StartToStart",window.event.srcElement.createTextRange())
        if(s.text==""){
        var strId=objId.substring(1,2);
        var strId1=objId.substring(2,3);
        strIdLeft="t"+strId+(parseInt(strId1)-1)
        document.getElementById(strIdLeft)?document.getElementById(strIdLeft).focus():(document.getElementById("t"+(parseInt(strId)-1)+3)?document.getElementById("t"+(parseInt(strId)-1)+3).focus():"")
        }
        }
        if(window.event.keyCode==39){
        var s=document.selection.createRange();
        s.setEndPoint("StartToStart",window.event.srcElement.createTextRange())
        if(s.text==obj.value){
        var strId=objId.substring(1,2);
        var strId1=objId.substring(2,3);
        strIdLeft="t"+strId+(parseInt(strId1)+1)
        document.getElementById(strIdLeft)?document.getElementById(strIdLeft).focus():(document.getElementById("t"+(parseInt(strId)+1)+1)?document.getElementById("t"+(parseInt(strId)+1)+1).focus():"")
        }
        }
        if(window.event.keyCode==38||window.event.keyCode==40){
        var strId=objId.substring(1,2);
        var strId1=objId.substring(2,3);
        window.event.keyCode==38?strIdLeft=("t"+(parseInt(strId)-1))+strId1:strIdLeft=("t"+(parseInt(strId)+1))+strId1
        document.getElementById(strIdLeft)?document.getElementById(strIdLeft).focus():""
        }
       
    }
}
</script>
</HEAD>
<BODY >
<table id="tab">
<tr>
<td><input type="text" name="t11" id="t11" ></td>
<td><input type="text" name="t12" id="t12" ></td>
<td><input type="text" name="t12" id="t13" ></td>
</tr>
<tr>
<td><input type="text" name="t21" id="t21" ></td>
<td><input type="text" name="t22" id="t22" ></td>
<td><input type="text" name="t22" id="t23" ></td>
</tr>
<tr>
<td><input type="text" name="t31" id="t31" ></td>
<td><input type="text" name="t32" id="t32" ></td>
<td><input type="text" name="t32" id="t33" ></td>
</tr>
<tr>
<td><input type="text" name="t41" id="t41" ></td>
<td><input type="text" name="t42" id="t42" ></td>
<td><input type="text" name="t42" id="t43" ></td>
</tr>
</table>
<input type=hidden id="hidden1" value="">
</BODY>
</HTML>
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值