You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将HTML密码输入框的默认圆点掩码修改为星号(*)

密码输入框修改默认掩码为星号的实现方案

原生 <input type="password"/> 的掩码字符由浏览器、操作系统默认规则控制,没有提供标准HTML属性直接修改掩码样式,可通过以下两种方案实现星号掩码效果:


方案1:CSS私有属性实现(WebKit内核兼容)

适合仅需要兼容Chrome、新版Edge、Safari等WebKit内核浏览器的场景,直接给密码输入框添加CSS样式即可:

input[type="password"] {
  /* 可选值:disc(默认圆点) / circle / square / asterisk(星号) */
  -webkit-text-security: asterisk;
}

注意:该属性为WebKit内核私有属性,不兼容火狐、旧版IE等非WebKit浏览器


方案2:JS模拟实现(全浏览器兼容)

如果需要全浏览器兼容,可以用普通文本输入框模拟密码输入逻辑,实际存储真实密码值,输入框只显示等长星号:

示例代码

<!-- 不用原生password类型,改用text类型 -->
<input type="text" id="customPassword">
// 存储真实的密码内容
let realPwd = '';
const pwdInput = document.getElementById('customPassword');

pwdInput.addEventListener('input', function(e) {
  const currentValue = e.target.value;
  const cursorPosition = e.target.selectionStart;
  const valueLength = currentValue.length;

  // 处理删除、输入、选中替换等不同场景的真实密码更新
  if (valueLength < realPwd.length) {
    // 删除字符场景
    const deleteLength = realPwd.length - valueLength;
    realPwd = realPwd.slice(0, cursorPosition) + realPwd.slice(cursorPosition + deleteLength);
  } else {
    // 新增/替换字符场景
    const addStr = currentValue.slice(cursorPosition - (valueLength - realPwd.length), cursorPosition);
    realPwd = realPwd.slice(0, cursorPosition - addStr.length) + addStr + realPwd.slice(cursorPosition - addStr.length);
  }

  // 输入框显示等长星号
  e.target.value = '*'.repeat(realPwd.length);
  // 重置光标位置,避免输入时光标自动跳到末尾
  e.target.selectionStart = e.target.selectionEnd = cursorPosition;
});

*注意事项:

  • 表单提交时要使用存储的realPwd作为密码值提交,不要取输入框的value
  • 可额外添加禁止选中、禁止右键复制的逻辑,避免用户误操作泄露相关内容
  • 如需支持密码管理器自动填充,需要额外添加对应的监听处理逻辑*

内容的提问来源于stack exchange,提问作者GccGUY

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 12:30:01