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').οnclick=setPass;

效果如下

 

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

 

转载于:https://www.cnblogs.com/wxcbg/p/10880713.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值