在我们平常使用手机的时候,注册一些软件或者账号的时候都会让我们输入短信验证码,那么今天我们就模仿一下短信验证码的样式和功能。
第一种
javascript部分
<script type="text/javascript">
$(() => {
var valCodeInput = $('#val-code-input');
var valCodeItems = $("div[name='val-item']");
var regex = /^[\d]+$/;
var valCodeLength = 0;
$('#val-box').on('click', () => {
valCodeInput.focus();
})
valCodeInput.on('input propertychange change', (e) => {
valCodeLength = valCodeInput.val().length;
if (valCodeInput.val() && regex.test(valCodeInput.val())) {
$(valCodeItems[valCodeLength - 1]).addClass('available');
$(valCodeItems[valCodeLength - 1]).text(valCodeInput.val().substring(valCodeLength - 1, valCodeLength));
}
})
$(this).on('keyup', (e) => {
if (e.keyCode === 8) {
$(valCodeItems[valCodeLength]).removeClass('available');
$(valCodeItems[valCodeLength]).text("");
}
});
})
function checkForNum(obj) {
obj.value = obj.value.replace(/[\D]/g, '');
}
</script>
html部分
<div class="container" id="test">
<div class="val-box" id="val-box">
<input id="val-code-input" type="text" maxlength="6" onkeyup="checkForNum(this)" onselectstart="return false;"
onblur="checkForNum(this)" />
<div name="val-item"></div>
<div name="val-item"></div>
<div name="val-item"></div>
<div name="val-item"></div>
<div name="val-item"></div>
<div name="val-item"></div>
</div>
</div>
css部分
.container {
margin-top: .5333rem;
}
.val-box {
display: flex;
justify-content: space-around;
align-items: center;
}
.val-box input[type=text] {
position: absolute;
left: 0;
top: 0;
height: .9067rem;
width: 212px;
opacity: 0.9;
z-index: -999;
outline: none;
}
.val-box div {
width: 1.2rem;
height: 1.2rem;
border: .0267rem solid #DDD;
border-radius: .1333rem;
display: flex;
align-items: center;
justify-content: center;
}
.val-box .available {
border-color: #76181c;
}
第一种
javascript部分
<script type="text/javascript">
$('.now').keyup(function () {
if ($(this).index() < 6) {
$(this).next('input').focus();
}
});
</script>
html部分
<div class="center">
<input type='text' name='code[]' class='now' maxlength="1" />
<input type='text' name='code[]' class='now' maxlength="1" />
<input type='text' name='code[]' class='now' maxlength="1" />
<input type='text' name='code[]' class='now' maxlength="1" />
<input type='text' name='code[]' class='now' maxlength="1" />
<input type='text' name='code[]' class='now' maxlength="1" />
</div>
css部分
.center{
display: flex;
justify-content: space-around;
margin-top: .5333rem;
}
input{
width: 1.2rem;
height: 1.2rem;
text-align: center;
}
.now{
/* width:1.8667rem; */
/* height:1.8667rem; */
border:.0267rem #cccccc solid;
}
.now:focus{
border:.0267rem #587d18 solid;
}