手机号4位显示空格,银行卡每4位显示空格
开发有时候会遇到输入手机号和银行卡号,按照每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"> <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>
相关推荐
wuxiaosi0 2019-12-16
bcbeer 2019-11-11
Elements小帅 2018-09-14
zhoushanhsan 2008-07-17
wuyufa 2019-07-01
hang0 2017-11-06
MichaelFreeman 2012-02-21
moguibeijing 2019-06-26
庆华 2019-06-26
xiaofeisi 2014-12-30
chaicheng0 2014-12-21
whoandyou 2014-09-17
mongkongstart 2013-07-28
Thanaos 2015-08-28
Lxiaofei 2018-09-23
AI产品经理Pipi 2019-03-11
九三智能控 2017-06-21