在项目中遇到这样一个问题,需要控制输入框只能输入一位并且是数字,查阅资料后整理了如下代码:
<div class="main-out">
<p class="identifying-title">输入企业提供的验证码</p>
<div class="pass-box">
<!--黑色横线框-->
<div class="pass-line">
<div class="line-box"><span class="line line-one"></span></div>
<div class="line-box"><span class="line line-two"></span></div>
<div class="line-box"><span class="line line-three"></span></div>
<div class="line-box"><span class="line line-four"></span></div>
<div class="line-box"><span class="line line-five"></span></div>
<div class="line-box"><span class="line line-six"></span></div>
</div>
<!--输入验证码框-->
<div class="passInput" id="on">
<input type="text" class="inputCont inputCont-one" maxlength="1" />
<input type="text" class="inputCont inputCont-two" maxlength="1"/>
<input type="text" class="inputCont inputCont-three" maxlength="1"/>
<input type="text" class="inputCont inputCont-four" maxlength="1"/>
<input type="text" class="inputCont inputCont-five" maxlength="1"/>
<input type="text" class="inputCont inputCont-six" maxlength="1"/>
<!--<input type="text" onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')" maxlength = 1>-->
</div>
</div>
</div>
$(".inputCont-one").focus();
$(".line-one").hide()
onload = function(){
var txts = on.getElementsByTagName("input");
for(var i = 0; i<txts.length;i++){
var t = txts[i];
t.index = i;
t.setAttribute("readonly", true);
t.onkeyup=function(){
if(this.value=this.value.replace(/\D/g,'')) {
var next = this.index + 1;
if(next > txts.length - 1) return;
txts[next].removeAttribute("readonly");
txts[next].focus();
$(".line-box").eq(next).find(".line").hide();
}else{
$(this).focus();
}
}
}
txts[0].removeAttribute("readonly");
}