js手机号4位显示空格,银行卡每4位显示空格效果
苏小麦麦 人气:0开发有时候会遇到输入手机号和银行卡号,按照每4位显示一个空格的需求,方便用户阅读,如果是纯展示,就很容易实现,如果是一边输入一边展示则有点难度
有人用两个input实现,一个负责输入数据,但是透明看不见,另外一个展示在界面上,变相的解决了这个需求(手机上可调用数字键盘)
本次取巧写个demo,只用一个input用定时器不断的查询输入的字符来判断输入的数据(无法直接调用数字键盘,因为里边有空格)
如果是银行卡号,将字符判断长度更改为,也可以根据实际需求来判断长度
lastLen === 5 || lastLen === 10 || lastLen === 15|| lastLen === 20
话不多说,上代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="renderer" content="webkit"> <title>Title</title> </head> <body> <input type="text" id="telphone"><span id="err"></span> <script> var telphone = document.getElementById('telphone'); var err = document.getElementById('err'); //定义两个缓存值 var firstLen = 0; var lastLen = 0; var re=/^1(3|4|5|7|8)\d{9}$/; telphone.oninput = function () { telphone.value = telphone.value.substr(0, 13);//只允许输入11位+2个空格 //用户输入满11位开始验证 if(telphone.value.length==13){ //将数据去掉空格后验证 if(!re.test(telphone.value.replace(/\s/g, ''))){ err.innerHTML='手机号码有误' } else{ err.innerHTML='' } }else{ err.innerHTML='' } } telphone.onfocus = function () { timer = setInterval(function () { lastLen = telphone.value.length; if (lastLen > firstLen) { firstLen = telphone.value.length; if (lastLen === 4 || lastLen === 9) { var temp1 = telphone.value.substr(0, telphone.value.length - 1); var temp2 = telphone.value.substr(telphone.value.length - 1); telphone.value = temp1 + ' ' + temp2; } } else if (lastLen <= firstLen) { if (lastLen === 4 || lastLen === 9) { telphone.value = telphone.value.substr(0, telphone.value.length - 1); } firstLen = telphone.value.length; } }, 10);//如果手机出现卡顿,可适当把定时器时间加大 } </script> </body> </html>
加载全部内容