转载

JS实现方向键切换输入框焦点的方法

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JS方向键切换输入框焦点</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<table border="1" id="mm" onkeydown="keyDown(event)"> 
<tr> <td> <input value="0"> </td> <td> <input> </td> <td> <input> </td> <td> <input> </td> </tr> 
<tr> <td> <input value="4"> </td> <td> <input> </td> <td> <input> </td> <td> <input> </td> </tr> 
<tr> <td> <input value="8"> </td> <td> <input> </td> <td> <input> </td> <td> <input> </td> </tr> 
<tr> <td> <input value="12"> </td> <td> <input> </td> <td> <input> </td> <td> <input> </td> </tr> 
<tr> <td> <input value="16"> </td> <td> <input> </td> <td> <input> </td> <td> <input> </td> </tr> 
<tr> <td> <input value="20"> </td> <td> <input> </td> <td> <input> </td> <td> <input> </td> </tr> 
</table> 
<script language="javascript" type="text/javascript"> 
<!-- 
var inputs=document.getElementById("mm").getElementsByTagName("INPUT"); 
function keyDown(event) 
{ 
 var focus=document.activeElement; 
 if(!document.getElementById("mm").contains(focus)) return; 
 var event=window.event||event;
 var key=event.keyCode; 
 for(var i=0; i<inputs.length; i++) 
 { 
  if(inputs[i]===focus) break; 
 } 
 switch(key) 
 { 
  case 37: 
   if(i>0) inputs[i-1].focus(); 
   break; 
  case 38: 
   if(i-4>=0) inputs[i-4].focus(); 
   break; 
  case 39: 
   if(i<inputs.length-1) inputs[i+1].focus(); 
   break; 
  case 40: 
   if(i+4 <inputs.length) inputs[i+4].focus(); 
   break; 
 } 
} 
//--> 
</script> 
</body>
</html>

原文地址:https://www.jb51.net/article/71263.htm

正文到此结束
Loading...