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

如何仅用原生JavaScript实现多密码框显示/隐藏切换功能

原生JavaScript实现多密码框的显示/隐藏功能

下面是完全基于原生JS的实现方案,支持任意数量的密码字段,无需依赖jQuery/Zepto:

示例HTML结构

先确保每个密码输入框和切换图标放在同一个容器内(用.password-group类标识):

<div class="password-group">
  <input type="password" class="password-input" placeholder="设置密码">
  <i class="fa fa-eye" aria-hidden="true"></i>
</div>

<div class="password-group">
  <input type="password" class="password-input" placeholder="确认密码">
  <i class="fa fa-eye" aria-hidden="true"></i>
</div>

原生JS实现代码

方案1:事件委托(推荐,支持动态添加的密码框)

这种方式通过监听文档的点击事件,自动匹配所有图标,哪怕是后续动态生成的密码组也能生效:

document.addEventListener('click', function(e) {
  const targetIcon = e.target;
  // 只处理眼睛图标点击
  if (!targetIcon.classList.contains('fa-eye') && !targetIcon.classList.contains('fa-eye-slash')) return;

  // 找到当前组内的密码输入框
  const passwordInput = targetIcon.closest('.password-group').querySelector('.password-input');
  
  // 切换图标样式
  targetIcon.classList.toggle('fa-eye');
  targetIcon.classList.toggle('fa-eye-slash');
  
  // 切换输入框的密码显示状态
  passwordInput.type = passwordInput.type === 'password' ? 'text' : 'password';
});

方案2:直接绑定事件(适合静态页面)

如果页面中的密码组都是静态加载的,也可以直接遍历所有图标绑定点击事件:

const passwordToggleIcons = document.querySelectorAll('.fa-eye, .fa-eye-slash');

passwordToggleIcons.forEach(icon => {
  icon.addEventListener('click', function() {
    const passwordInput = this.closest('.password-group').querySelector('.password-input');
    
    this.classList.toggle('fa-eye');
    this.classList.toggle('fa-eye-slash');
    passwordInput.type = passwordInput.type === 'password' ? 'text' : 'password';
  });
});

关键逻辑说明

  • 容器关联:用closest('.password-group')精准定位当前图标所属的密码组,确保操作不会影响其他密码框
  • 类切换:classList.toggle()简化了图标样式的切换逻辑,无需手动判断移除/添加类
  • 类型切换:直接修改输入框的type属性,在password和text之间切换实现显示/隐藏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 16:05:25