手机号344格式化处理

 尝试过多种写法,在安卓机app里内嵌H5出现光标自动前进等bug头大无法解决。最后从jd借鉴如下代码。

 

<input type="tel" id="J-mobile" maxlength="13" placeholder="请输入充值号码" value="">

<script>
var flow = {
initIndex:function(){
flow.initMobile();
$("#J-mobile").on('blur',function (){
flow.initMobile();
});
// 手机号码输入框
$("#J-mobile").on('keyup',function(){
var a =this;
var num = flow.getNum(a.value), len = num.length;
var se,vlen;
var oEvent = window.event;
// 手机号码加空格
if(a.setSelectionRange) {
se = a.selectionEnd;
vlen = se === a.value.length;
}
if(12 > len) {
a.value = flow.formatMobile(num);
if(11 === len) {
a.blur();
return;
}
} else {
a.value = flow.formatMobile(num.substr(0,11));
a.blur();
}
se && setTimeout(function(){
vlen && (se = a.value.length);
a.setSelectionRange(se,se)
},0)
});


},
// 号码初始化
initMobile: function(){
var $mobile = $("#J-mobile");
var mobile = $mobile.val();
if (mobile.indexOf(" ") == -1) {
if (mobile.length > 3) {
mobile = mobile.substring(0, 3) + " " + mobile.substring(3)
}
if (mobile.length > 8) {
mobile = mobile.substring(0, 8) + " " + mobile.substring(8)
}
}
$mobile.val(mobile);
},


getNum :function(a,b) {
var num = $.trim(a);
num = num.replace(/[^\d]/g,"");
return num;
},
formatMobile :function(a){
var num = (a + "").split("")
,str = "";
num.forEach(function (a,num){
(3 === num || 7===num) && (str +=" ");
str += a;
});
return str;
},
}
flow.initIndex();

</script>

posted @ 2017-11-24 11:26  锅巴菜  阅读(686)  评论(0编辑  收藏  举报