输入框,手机号输入,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
本文仅提供参考,是本人闲时所写笔记,如有错误,还请赐教,作者:阿蒙不萌,大家可以随意转载