本文實例講述了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程序設計有所幫助。