方式一:单纯的手机号
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>手机号空格填充</title>
<script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
function getMoblieFormat(obj)
{
var value = obj.value;
value = value.replace(/\s+/g, "");
var a1=4,len=0;
var result = [];
for(var i = value.length-1; i >=0; i--){
len++;
if(len==4){
result.push(" " + value.charAt(i));
}else if(len==8){
result.push(" " + value.charAt(i));
}else if(len==11){
result.push(" " + value.charAt(i));
}else{
result.push(value[i]);
}
}
obj.value = result.reverse().join("");
}
</script>
</head>
<body>
手机号:
<input type="text" id="tel" value="" placeholder="请输入手机号。。。" onkeyup="getMoblieFormat(this)" />
</body>
方式二:有无区号都可以
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>手机号空格填充</title>
<script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
function getMoblieFormat(obj)
{
var value = obj.value;
value = value.replace(/\s+/g, "");
console.log(value);
value=value.replace(/[^\d]/g,"");
console.log(value);
// value = value.replace(/\s*/g, "");
var result = [];
for(var i = 0; i < Math.min(value.length,11); i++){
if (i==3||i==7){
// console.log(value.charAt(i));
result.push(" " + value.charAt(i));
}else{
result.push(value.charAt(i));
}
}
obj.value = result.join("");
}
</script>
</head>
<body>
手机号:
<input type="text" id="tel" value="" placeholder="请输入手机号。。。" onkeyup="getMoblieFormat(this)" />
</body>