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

使用Bootstrap 5时密码输入框右侧眼睛图标无法显示问题

Bootstrap v5 + FontAwesome v5 密码输入框图标&布局异常修复方案

问题根因分析

  • 图标不显示:你使用的far fa-eye-slash属于FontAwesome Regular风格图标,绝大多数开发者引入的免费版FontAwesome默认只包含Solid(fas)风格资源,Regular图标未加载就会出现空白。另外你写的JS切换逻辑只新增了fa-eye类,没有移除原有fa-eye-slash类,两个图标类共存也会导致显示异常。
  • 密码输入框偏右:你的两个input-group子元素数量不一致,用户名输入组只有2个子元素(前缀+输入框),密码输入组有3个子元素(前缀+输入框+后缀),如果存在自定义样式覆盖了Bootstrap默认的form-control自适应规则,就会出现宽度不一致、位置偏移的问题,另外你没有给输入框声明type属性,浏览器默认样式也可能引发布局异常。

修复步骤

  1. 把眼睛图标前缀从far改为fas,使用Solid风格的通用图标,无需额外引入资源
  2. 调整JS切换逻辑,同步切换fa-eye和fa-eye-slash两个类
  3. 补全输入框的type属性,保证浏览器默认样式正常
  4. 如果修改后仍存在布局偏移,可在自定义CSS中添加如下规则,强制输入框自适应填充剩余宽度:
.input-group .form-control {
  flex: 1 1 auto !important;
}

修正后代码

HTML代码

<div class="input-group mb-3">
   <span class="input-group-text"><i class="fas fa-lock"></i></span>
   <input type="text" class="form-control" id="username" name="username" placeholder="Username" value="">
</div>

<div class="input-group mb-3">
   <span class="input-group-text"><i class="fas fa-lock"></i></span>
   <input type="password" class="form-control" id="password" name="password" placeholder="Password" value="">
   <span class="input-group-text"><i class="fas fa-eye-slash" id="togglePassword"></i></span>
</div>

JavaScript代码

const togglePassword = document.querySelector("#togglePassword");
const password = document.querySelector("#password");

togglePassword.addEventListener("click", function () {
    // 切换输入框type属性
    const type = password.getAttribute("type") === "password" ? "text" : "password";
    password.setAttribute("type", type);
    // 切换眼睛图标
    this.classList.toggle('fa-eye');
    this.classList.toggle('fa-eye-slash');
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:45:00