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事件的,把用戶輸入的字符轉換成星號顯示,第二個才是真正用來提交數據的(第二個得隱藏)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM