表单自动切换焦点

时间过的真是很快,转眼六月份已经过去一半了。

感叹完毕回到正题。早上在看《javascript高级程序设计》,看到自动切换焦点的功能,这个功能确实不错,于是做起来。学到了onkeyup这个事件。

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>自动切换焦点</title>
 6 <style type="text/css">
 7 input { width:50px; }
 8 </style>
 9 </head>
10 
11 <body>
12     <form action="" id="autofocus">
13         <input type="text" maxlength="4" />
14         <input type="text" maxlength="4" />
15         <input type="text" maxlength="4" />
16         <input type="text" maxlength="4" />
17     </form>
18     <script type="text/javascript">
19     var oIn = document.getElementById("autofocus").getElementsByTagName("input");
20     for(var i=0; i<oIn.length; i++) {
21         (function(m){
22             if(m<oIn.length-1) {
23                 oIn[m].onkeyup = function() {
24                     if(oIn[m].value.length === oIn[m].maxLength) {
25                         oIn[m+1].focus();
26                     }
27                 };
28             }
29         })(i);
30     }
31     </script>
32 </body>
33 </html>

后来想想加入键盘控制焦点会更好。当然,还不是很完美。

 1     var oIn = document.getElementById("autofocus").getElementsByTagName("input");
 2     for(var i=0; i<oIn.length; i++) {
 3         (function(m){            
 4             oIn[m].onkeydown = function(e) {
 5                 //IE下将window.event赋值给theEvent
 6                 //FF下将e赋值给theEvent
 7                 var theEvent = window.event||e;
 8                 var keycode = theEvent.which || theEvent.keyCode;
 9                 if(keycode === 39 && m<oIn.length-1) {
10                     oIn[m+1].focus();
11                 }
12                 if(keycode === 37 && m>0) {
13                     oIn[m-1].focus();
14                 }
15             };
16             
17             oIn[m].onkeyup = function() {
18                 if(oIn[m].value.length === oIn[m].maxLength && m<oIn.length-1) {
19                     oIn[m+1].focus();
20                 }
21             };
22         })(i);
23     }
posted @ 2012-06-14 11:21  长风freedom  阅读(192)  评论(0编辑  收藏  举报