js控制四個數字加空格(銀行卡)而且支持插入數字(解決光標跳動問題)

通常來講,爲了便於用戶輸入,銀行卡號會每四個數字用空格隔開,這個在前端使用正則表達式不難作到,可是容易出現不能從數字中間插入的問題:光標移動到中間,輸入一個數字後光標便自動跳轉到最右了。javascript

上述問題很是影響用戶體驗,通過一段時間的研究,我用如下辦法解決了此問題:html

##Input前端

這裏使用了type="tel",這樣是爲了在移動端調出數字鍵盤,H5的新特性pattern也能夠實現,可是這個屬性的兼容性並非很好。java

<input type="tel" placeholder="請輸入儲蓄卡卡號" name="cardNum">

##監控輸入正則表達式

js針對input有個屬性selectionStart,這個是當前光標所在的位置,那麼咱們只要獲取了這個位置,哪怕以後它跳到了最右,咱們也能夠控制它回到原來的位置。優化

//監控input事件
document.querySelector('input[name=cardNum]').addEventListener('input', function() {
    //獲取當前光標位置
    var position = this.selectionStart;
    var v = this.value;
    //四個字符加一個空格
    this.value = v.replace(/\s/g, '').replace(/(.{4})/g, "$1 ");
    //優化語句:若是當前位置是空格字符,則自動清除掉
    if (this.value.charAt(this.value.length - 1) == ' ') {
        this.value = this.value.substring(0, this.value.length - 1);
    }
    var input = this;
    //從新定位光標位置,start和end都須要設置,否則就是截取片斷了
    input.selectionStart = position + countSpace(this.value, position);
    input.selectionEnd = position + countSpace(this.value, position);
})
相關文章
相關標籤/搜索