jquery键盘事件实现enter、上下左右切换input焦点
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>表单事件 and 键盘事件and 回车和小键盘切换input焦点</title>
<style type="text/css">
.color
{
background-color: rgb(77,198,227);
border-color: white;
}
input
{
line-height: 25px;
border-color: red;
}
</style>
<script type="text/javascript" src="../jquery-1.8.3.js"></script>
<script type="text/javascript">
//回车和小键盘切换input焦点
function getfocus(thisinput)
{
var inputs = document.getElementsByTagName("input");
if(event.keyCode == 13 || event.keyCode == 40 || event.keyCode == 39) {
for (var i=0; i < inputs.length; i++) {
if (thisinput == inputs[i])
{
if (i == (inputs.length - 1 ))
{
inputs[0].focus();
break;
}
else
{
inputs[i + 1].focus();
break;
}
}
}
}
else if(event.keyCode == 38 || event.keyCode == 37) {
for (var i=0; i < inputs.length; i++) {
if (thisinput == inputs[i])
{
if(i != 0)
{
inputs[i - 1].focus();
break;
}
else
{
inputs[inputs.length - 1].focus();
break;
}
}
}
}
}
$(function()
{
$("input").change(function()
{
$(this).css("border","double");
});
$("input").bind({focus:function()
{
$(this).addClass("color");
},
blur:function()
{
$(this).removeClass("color");
}});
$("input").keydown(function(event)
{
var thisinput = $(this)[0];
getfocus(thisinput);
});
});
</script>
</head>
<body>
<input type="text" name="txt"><br/><br/>
<input type="text" name="txtName"><br/><br/>
<input type="text" name="Name"><br/><br/>
</body>
</html>