六位字符密碼輸入器

老規矩~ 上DEMO,過過癮先:六位字符密碼輸入器
再上源碼:六位字符密碼輸入器git

從DEMO中我看能夠看出,首先只能輸入六個字符,而且僅容許輸入數字,在輸入六位數字完成以後會自動執行一個回調(DEMO中是將輸入結果顯示出來了)github

一. 先說原理

首先呢,咱們須要兩個東東:其一是一個真是的輸入框,即:真正處於焦點狀態並獲取用戶輸入的input;其二是一組僞輸入框,即:並無真正獲取焦點,但只是顯示了當前輸入的值(固然啦,密碼嘛,只有一個小黑點而已~)。ui

其次呢,咱們須要簡單不懼一下,讓着一組(6個)僞造元素恰好重疊在真實輸入框的下方。以下:this

圖片描述

邊距實際是沒有的啦~,途中只是爲了看着更清晰一些。spa

另外,咱們須要把頂層的真是輸入框opcity設爲0,這樣其實呈如今用戶面前的就是這一組僞造的輸入框啦。.net

可是用戶其實再輸入的時候仍是對真是輸入框進行操做,在以後咱們在講用戶的輸入依次填寫到僞造輸入框裏邊就能夠嘍~code

很簡單吧~事件

二. 碼代碼

首先初始化各個DOM,以及綁定輸入事件。圖片

function init(fun){
    var that = this;
    this.callback = fun;
    that.realInput = container.children[0];
    that.bogusInput = container.children[1];
    that.bogusInputArr = that.bogusInput.children;
    that.maxLength = that.bogusInputArr[0].getAttribute("maxlength");
    that.realInput.oninput = function(){
        that.setValue();
    }
    that.realInput.onpropertychange = function(){
        that.setValue();
    }
}

而後在用戶輸入時分別將用戶輸入輸入到僞造輸入框中ci

function setValue(){
    this.realInput.value = this.realInput.value.replace(/\D/g,"");
    console.log(this.realInput.value.replace(/\D/g,""))
    var real_str = this.realInput.value;
    for(var i = 0 ; i < this.maxLength ; i++){
        this.bogusInputArr[i].value = real_str[i]?real_str[i]:"";
    }
    if(real_str.length >= this.maxLength){
        this.realInput.value = real_str.substring(0,6);
        this.callback();
    }
}

最後咱們輸入密碼固然是要獲取的啦~,來一個獲取最終值的方法~

function getBoxInputValue(){
    var realValue = "";
    for(var i in this.bogusInputArr){
        if(!this.bogusInputArr[i].value){
            break;
        }
        realValue += this.bogusInputArr[i].value;
    }
    return realValue;
}
相關文章
相關標籤/搜索