如何在 html 文本输入中"hide"密码



我目前正在构建一个表单,其中我有一个密码。

是一种保持输入类型为text而密码保持"隐藏"的方法。

基本上,它不是显示在文本框中:

mypassword

我想让它说:

*********

之类的。基本上就是让用户输入的文本不可见。

我知道将类型更改为password将是一个解决方案,但我需要保持类型为text

这可能有用的一个原因是临时显示最后输入的字符,就像在移动设备上一样:

function passwordInput(el)
{
//already initialized?
if (el.actualValue !== undefined)
return el;
let timer = null;
el.actualValue = el.value;
el.addEventListener("input", e =>
{
clearTimeout(timer);
const val = el.value,
start = el.selectionStart,
end = el.selectionEnd,
len = val.length - el.actualValue.length,
//find none-hidden characters
diff = (val.substring(0, start).match(/[^●]+/g)||[""])[0],
//this will be shown for nn seconds
last = diff === "" ? "" : diff[diff.length - 1],
//replace all characters with hidden character
vis = "".padStart(val.length, "●");
//record new value
el.actualValue = el.actualValue.substring(0, start - diff.length) + diff + el.actualValue.substring(start - len);
//replace visible value with hidden characters, except for the last "new" character
el.value = vis.substring(0, start - last.length) + last + vis.substring(start);
//set cursor back to it's original position
el.selectionStart = start;
el.selectionEnd = end;
//hide entire visible value after nn seconds
timer = setTimeout(() =>
{
const start = el.selectionStart,
end = el.selectionEnd;
el.value = vis;
el.selectionStart = start;
el.selectionEnd = end;
}, 1000); // 1 second delay
});
if (el.value !== "")
el.dispatchEvent(new Event("input"))
return el;
}
passwordInput(document.getElementById("myInput")).addEventListener("input", e =>
{
//display real value
output.textContent = e.target.actualValue;
});
<input type="text" id="myInput" autocomplete="off">
<div>Actual value: <span id="output"></span><div>

基本上,它所做的是将实际值存储在inputElement.actualValue属性中,并用"●"代替值。的性格。有一个扭结我没有费心去看,是选择重置当最后一个字符被隐藏。

最新更新