輸入框,手機號輸入,344格式(jQuery和Vue)


一、jquery

function fomatterTel(val, old) {//val: 當前input的值,old: input上次的值
            var str = "";
            var telLen = val.length;
            if (old.length <= telLen) {
                if (telLen === 4 || telLen === 9) {
                    var pre = val.substring(0, telLen-1);
                    var last = val.substr(telLen-1, 1);
                    str = pre + ' ' + last;
                } else {
                    str = val;
                }
            } else {
                if (telLen === 9 || telLen === 4) {
                    str = val.trim();
                } else {
                    str = val;
                }
            }
            return str;
        }

每次傳入新的val和舊的val,就可以啦。

注:

1.input的輸入事件最好用oninput事件監聽,用keyup的話會有閃爍,不過看不太出來,也能用。jquery的input事件要用bind綁定,不能直接寫$("#input1").input這樣寫會報錯, 要寫成$("#input1").bind('input', function(){});

2.old的獲取也很簡單

var oldTelephone = $("#telephone").val();//輸入前先獲取一次
 $("#telphone").bind('input',function () {
        $("#telephone").val(fomatterTel($("#telephone").val(), oldTelephone));
        oldTelephone = $("#telephone").val();//輸入后保存old為下一次輸入做准備
 });

二、vue中

一樣的,只不過vue中更好獲取old,data中存入telephone: ''。input的v-model為telephone 。在watch中監聽telephone

<input v-model='telephone'>
 
 
data () {
    return {
        telephone: ''
    }
},
watch: {
    telephone (newValue, oldValue) {
        if (newValue > oldValue) {
          if (newValue.length === 4 || newValue.length === 9) {
            var pre = newValue.substring(0, newValue.length - 1);
            var last = newValue.substr(newValue.length - 1, 1);
            this.telephone = pre + ' ' + last;
          } else {
            this.telephone = newValue;
          }
        } else {
          if (newValue.length === 9 || newValue.length === 4) {
            this.telephone = this.telephone.trim();
          } else {
            this.telephone = newValue;
          }
        }
     }
}

 

 

來源:https://blog.csdn.net/qq_38627581/article/details/80599485


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM