`

javascript使用方向键控制光标在table单元格的输入框的中跳动

阅读更多
<html>
<head>
<script type="text/javascript">
//索引,全局变量
var text_ind;
function of(text_index){
text_ind = text_index;
}

function okd(text_value){
var code_value = event.keyCode;
var next_name;
var flag = false;

var rng = document.selection.createRange();
rng.moveStart("character",-document.getElementById("t"+text_ind).value.length);
var gb_index = rng.text.length;

//判断按键是否为 -->
if(code_value==39){
  //如果光标所在位置不是最后一个文本框,
  //当光标不是最后一个且光标是在文本值最后时发生
if(text_ind!=8 && gb_index==3){
flag = true;
next_name = "t"+(text_ind+1);
}
}

//判断按键是否为 <--、
//当光标不是最后一个且光标是在文本值最前时发生
if(code_value==37){
if(text_ind !=0 && gb_index==0){
flag = true;
next_name = "t"+(text_ind-1);
}
}

//判断按键是否为 向上键
if(code_value==38){
//如果光标所在位置不是在第一行!
if(text_ind!=0 && text_ind!=1 && text_ind!=2){
flag = true;
next_name = "t"+(text_ind-3);
}
}

//判断按键是否为 向下键
if(code_value==40){
if(text_ind!=6 && text_ind!=7 && text_ind!=8){
flag = true;
next_name = "t"+(text_ind+3);
}
}
if(flag){
document.getElementById(next_name).focus();
}
}
</script>
</head>
<body>
<table align="center" width="100" height="50">
<!-- 下面的函数of()中传递的是索引(第几个文本框);函数okd()中传递的是text的值 -->
<tr>
<td> <input type="text" value="111" id="t0" onfocus="of(0)" onkeyup="okd('111')"/> </td>
<td> <input type="text" value="222" id="t1" onfocus="of(1)" onkeyup="okd('222')"/> </td>
<td> <input type="text" value="333" id="t2" onfocus="of(2)" onkeyup="okd('333')"/> </td>
</tr>
<tr>
<td> <input type="text" value="444" id="t3" onfocus="of(3)" onkeyup="okd('444')"/> </td>
<td> <input type="text" value="555" id="t4" onfocus="of(4)" onkeyup="okd('555')"/> </td>
<td> <input type="text" value="666" id="t5" onfocus="of(5)" onkeyup="okd('666')"/> </td>
</tr>
<tr>
<td> <input type="text" value="777" id="t6" onfocus="of(6)" onkeyup="okd('777')"/> </td>
<td> <input type="text" value="888" id="t7" onfocus="of(7)" onkeyup="okd('888')"/> </td>
<td> <input type="text" value="999" id="t8" onfocus="of(8)" onkeyup="okd('999')"/> </td>
</tr>
</table>
</body>
</html>

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics