对,@eric-yin 有正确答案:An input
withtype="password"
掩码密码。
尽管如此,就像@beefchimi 一样,我需要:一个密码字段,它可以:
- 在每个浏览器中显示星号
- 显示不带星号的最后一个字符
所以我写了这个 jQuery 插件:
$.fn.betta_pw_fld = function(pwfld_sel, hiddenfld_sel) {
// this is the form the plugin is called on
$(this).each(function() {
// the plugin accepts the css selector of the pw field (pwfld_sel)
var pwfld = $(this).find(pwfld_sel);
// on keyup, do the masking visually while filling a field for actual use
pwfld.off('keyup.betta_pw_fld');
pwfld.on('keyup.betta_pw_fld', function() {
// if they haven't typed anything...just stop working
var pchars = $(this).val();
if (pchars == '') return;
// we'll need the hidden characters too (for backspace and form submission)
var hiddenfld = $(this).parents('form').find(hiddenfld_sel);
var hchars = hiddenfld.val();
// use these placeholders to build our password values
// this one will have all asterisks except the last char
var newval = '';
// this one will have the actual pw in it, but we'll hide it
var newhpw = '';
// in this block, we're in a "keydown" event...
// let's get the characters entered
// loop over them and build newval and newhpw appropriately
for (i=0; i<pchars.length - 1; i++) {
if (pchars[i] == '*') {
newhpw += hchars[i];
} else {
newhpw += pchars[i];
}
newval += '*';
}
// we want to see the last character...
var lastchar = pchars[pchars.length - 1];
if (lastchar == '*') {
newval += hchars[pchars.length - 1];
newhpw += hchars[pchars.length - 1];
} else {
newval += pchars[pchars.length - 1];
newhpw += pchars[pchars.length - 1];
}
// set the updated (masked), visual pw field
$(this).val(newval);
// keep the pw hidden and ready for form submission in a hidden input
hiddenfld.val(newhpw);
});
});
};
html 可能是:
<form id="myForm">
<label for="pw">Type password:</label><br>
<input name="pw" class="stylishPassword" type="text"><br>
<input class="hiddenPassword" type="hidden">
</form>
并且在document.ready
或适当的时间,插件被实例化如下:
$('#myForm').betta_pw_fld('.stylishPassword', '.hiddenPassword')
访问更好的密码字段 jQuery 插件 Codepen,如果对您有帮助,请记得投票。