html
<div class="inputYZM">
<input type="tel" class="inputPhone" maxlength="1" name="code" pattern="[0-9]*" onkeyup="value=value.replace(/[^\d]/g,'')">
<input type="tel" class="inputPhone" maxlength="1" name="code" pattern="[0-9]*" onkeyup="value=value.replace(/[^\d]/g,'')">
<input type="tel" class="inputPhone" maxlength="1" name="code" pattern="[0-9]*" onkeyup="value=value.replace(/[^\d]/g,'')">
<input type="tel" class="inputPhone" maxlength="1" name="code" pattern="[0-9]*" onkeyup="value=value.replace(/[^\d]/g,'')">
</div>
css
.inputYZM input {
display: inline-block;
width: 0.8rem;
height: 0.96rem;
border: 3px solid #EEEEEE;
margin-right: 0.45rem;
text-align: center;
font-size: 0.48rem;
}
.inputYZM input:last-child {
margin-right: 0;
}
js
// //键盘输入事件
$('.inputYZM input').keyup(function (event) {
// 删除往前 添加往后
if ($(this).index() < 4) {
if (event.keyCode == 46 || event.keyCode == 8) {
$(this).prev('input').focus();
} else {
$(this).next('input').focus();
}
}
});
let active = 0;
let inputBtn = document.querySelectorAll('.inputPhone');
for (let i = 0; i < inputBtn.length; i++) {
inputBtn[i].addEventListener('click', function () {
inputBtn[active].focus();
}, false);
inputBtn[i].addEventListener('focus', function () {
this.addEventListener('keyup', listenKeyUp, false);
}, false);
inputBtn[i].addEventListener('blur', function () {
this.removeEventListener('keyup', listenKeyUp, false);
}, false);
}
function listenKeyUp() {
let oneInput = $(".inputYZM input:first-child").val(); //第一个
let towInput = $(".inputYZM input:nth-child(2)").val(); //第二个
let threeInput = $(".inputYZM input:nth-child(3)").val(); //第三个
let fourInput = $(".inputYZM input:nth-child(4)").val(); //第四个
//拼成完整的验证码
let fullInput = oneInput.toString() + towInput.toString() + threeInput.toString() + fourInput.toString();
}