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

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

上述問題非常影響用戶體驗,經過一段時間的研究,我用以下辦法解決了此問題:

Input

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

<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);
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章