js输入密文弹出数字键盘

我们经常被产品要求,在移动端的web页面上的输入框输入密码时要弹出数字键盘,而不是全键盘,这个该怎么实现呢?

1.首先要弹出数字键盘,我们只能把input框的type从password改为tel

2.但经过第一步,输入的内容会变成明文,这时候也要星号显示,改怎么实现

经过一番研究,找到如下的实现方法:

 1 function setPass(e) {
 2             var target = e.currentTarget,
 3                 idx = target.selectionStart,
 4                 val = $(target).val(),
 5                 nextval = $(target).next().val(),
 6                 maxLen = $(target).attr('maxlength') || 6,
 7                 single = val.slice(idx - 1, idx),
 8                 left = '',
 9                 right = '';
10             if (val.length == nextval.length) return;
11             if (val.length > nextval.length) { //添加
12                 if (/\d/g.test(single)) { //如果是数字
13                     left = nextval ? (nextval.slice(0, idx - 1) + single) : single;
14                     right = nextval.slice(idx - 1, maxLen);
15                 }
16                 if (/\D/g.test(single)) { //如果是非数字字符
17                     left = nextval ? nextval.slice(0, idx - 1) : '';
18                     right = nextval.slice(idx - 1, maxLen);
19                 }
20             }
21             if (val.length < nextval.length) { //删除
22                 left = nextval ? nextval.slice(0, idx) : '';
23                 right = nextval.slice(idx + 1, maxLen);
24             }
25             val = (left + right).replace(/\d/g, "●");
26             if (!val) {
27                 $(target).next().val(left + right);
28             } else {
29                 $(target).val(val).next().val(left + right);
30             }
31 
32         }

当输入框的input事件触发的时候调用以上方法

<input type='tel' id='psd'>

document.getElementById('psd').onclick=setPass;

效果如下

 

这里有两个input,为什么一个输入框要有两个input呢?因为第一个是用来触发setPass事件的,把用户输入的字符转换成星号显示,第二个才是真正用来提交数据的(第二个得隐藏)

猜你喜欢

转载自www.cnblogs.com/wxcbg/p/10880713.html