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

如何实现Bootstrap输入框与眼睛图标相邻布局(附代码示例)

实现Bootstrap输入框旁的密码可见性切换图标

要让输入框与眼睛图标无缝相邻,同时实现密码可见性切换,直接用Bootstrap的输入组组件就能搞定,以下是完整解决方案:

修改后的HTML代码

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="mb-3">
  <label class="form-label" for="current">Current Password</label>
  <!-- 用input-group容器包裹输入框和图标按钮,实现相邻布局 -->
  <div class="input-group">
    <input asp-for="ChangePassword.OldPassword" type="password" class="form-control" required autofocus />
    <button class="btn btn-light border-start-0 shadow-none" type="button" id="password-addon" tabindex="99">
      <i class="fa fa-eye"></i>
    </button>
  </div>
  <span asp-validation-for="ChangePassword.OldPassword" class="text-danger"></span>
</div>

核心调整点

  • 新增input-group容器:把输入框和按钮放入该容器,Bootstrap会自动处理两者的间距与边框衔接,无需手动调试样式。
  • 优化按钮样式:给按钮添加border-start-0类移除左侧边框,避免与输入框边框重复;保留shadow-none让按钮风格与输入框统一。
  • 显式设置密码类型:给输入框添加type="password",确保初始状态为密码隐藏模式。

密码切换功能代码

点击眼睛图标切换密码可见性,添加以下JavaScript代码:

document.getElementById('password-addon').addEventListener('click', function() {
  const passwordInput = document.querySelector('[asp-for="ChangePassword.OldPassword"]');
  const eyeIcon = this.querySelector('i');
  
  passwordInput.type = passwordInput.type === 'password' ? 'text' : 'password';
  eyeIcon.classList.toggle('fa-eye');
  eyeIcon.classList.toggle('fa-eye-slash');
});

这段代码会切换输入框的类型,同时切换眼睛图标样式,实现完整的交互效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:15:52