js 6位验证码输入自定义样式

html
<div class="yzm-cont">
         <input id="val-code-input" type="tel" maxlength="6" onkeyup="checkForNum(this)" onselectstart="return false;" onblur="checkForNum(this)" />
         <div class="my_input" name="val-item"></div>
          <div class="my_input" name="val-item"></div>
         <div class="my_input" name="val-item"></div>
        <div class="my_input" name="val-item"></div>
        <div class="my_input" name="val-item"></div>
        <div class="my_input" name="val-item"></div>
</div>
css
#yzmmodal div.yzm-cont{
    margin-top: 20px;
    justify-content: space-between;
}
#yzmmodal div.yzm-cont input{
    position: absolute;
    z-index: 0;
    width: 100%;
    height: 37px;
    border: none;
    outline: none;
    color: #fff;
}
#yzmmodal div.yzm-cont .my_input{
    width: 13%;
    height: 37px;
    outline: none;
    border: 1px solid rgba(140,140,140,1);;
    border-radius: 10px;
    caret-color: transparent;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 20;
}
#yzmmodal div.yzm-cont .my_input.available {
    border: 1px solid #0081db;
}
js
var valCodeInput = $('#val-code-input');
        var valCodeItems = $(".my_input");
        var regex = /^[\d]+$/;
        var valCodeLength = 0;
        valCodeInput.on('input propertychange change', (e) => {
            $(valCodeItems).each(function(i){
                if($(this).text() != ''){
                    $(this).addClass('available')
                } 
            })
            valCodeLength = valCodeInput.val().length;
            console.log("wode="+valCodeInput.val())
            if(valCodeLength == 6){
                console.log(valCodeLength)
                $(valCodeItems).addClass('available')
                $(valCodeItems[0]).text(valCodeInput.val()[0])
                $(valCodeItems[1]).text(valCodeInput.val()[1])
                $(valCodeItems[2]).text(valCodeInput.val()[2])
                $(valCodeItems[3]).text(valCodeInput.val()[3])
                $(valCodeItems[4]).text(valCodeInput.val()[4])
                $(valCodeItems[5]).text(valCodeInput.val()[5])
            }else{
                console.log(valCodeLength)
            }
            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, '');
        }
 
        $(".my_input").click(function(){
            $('#val-code-input').focus();
        })

猜你喜欢

转载自www.cnblogs.com/hlhs/p/11742276.html