本文实例讲述了javascript自动切换焦点控制的方法。分享给大家供大家参考,具体如下:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <html> <head> <script type="text/javascript" src="jquery-1.7.2.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ var EventUtil = { addHandler: function(element,type, handler){ if(element.addEventListener){ element.addEventListener(type,handler,false); }else if(element.attachEvent){ element.attachEvent("on"+type,handler); }else{ element["on"+type]=null; } }, removeHandle:function(element,type,handler){ if(element.removeEventListener){ element.removeEventListener(type,handler,false); }else if(element.detachEvent){ element.detachEvent("on"+type,handler); } }, getEvent:function(event){ return event ? event:window.event; }, getTarget:function(event){ return event.target || event.srcElement; }, preventDefault:function(event){ if(event.preventDefault){ event.preventDefault(); }else{ event.returnValue=false; } }, stopPropagation:function(event){ if(event.stopPropagation){ event.stopPropagation(); }else{ event.cancelBubble=true; } } }; var dom_text1=document.getElementById("text1"); var dom_text2=document.getElementById("text2"); var dom_text3=document.getElementById("text3"); function switchFocus(event){ event=EventUtil.getEvent(event); var target=EventUtil.getTarget(event); if(target.value.length==target.maxLength){ var form=target.form; for(var i=0;i<form.elements.length;i++){ if(form.elements[i]==target){ form.elements[i+1].focus(); return; } } } } EventUtil.addHandler(dom_text1,"keyup",switchFocus); EventUtil.addHandler(dom_text2,"keyup",switchFocus); EventUtil.addHandler(dom_text3,"keyup",switchFocus); }) </script> </head> <body> <form id="form1"> <input type="text" maxlength="3" id="text1"/> <input type="text" maxlength="3" id="text2"/> <input type="text" maxlength="3" id="text3"/> </br> <input type="text" /> </form> </body> </html>
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript动画特效与技巧汇总》、《javascript面向对象入门教程》及《JavaScript数据结构与算法技巧总结》
希望本文所述对大家JavaScript程序设计有所帮助。