本文示範如何讓多個相連的輸入框在填滿指定字數後,焦點自動跳到下一個輸入框,常用於身分證字號、驗證碼或銀行卡號的分段輸入。完整程式碼如下:
代碼如下:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>JS控制超過長度限制後自動跳轉下一個文本框</title>
</head>
<body>
<input type="text" size="10">
<input type="text" size="10">
<input type="text" size="10">
<script language="javascript">
function Each(arr,fn){for(var i=0,len=arr.length;i<len;i++){fn.call(arr[i],i,arr);};};
(function(inputs){
Each(inputs,function(i){
var _o=this;
this.onkeyup=function(){
if(_o.value.length>=4){
if(inputs[i+1]){
inputs[i+1].focus();
}else{
_o.value=_o.value.slice(0,4);
}
}
}
})
})(document.getElementsByTagName('input'));
</script>
</body>
</html>
關鍵是遍歷所有輸入框並各自綁定 onkeyup,當目前欄位字數達到 4 時,若還有下一格就呼叫它的 focus(),若是最後一格則用 slice 硬性截斷避免超填。這裡用自訂的 Each 函式搭配 call 讓回呼中的 this 指向當前元素,是相當靈活的寫法。希望本文對你的 JavaScript 開發有所幫助。