为密码输入框添加并定位Bootstrap密码可见切换图标
Bootstrap密码输入框可见切换图标正确实现方案
直接用Bootstrap原生的input-group组件就能完美解决定位问题,不用自己手动折腾相对/绝对定位,下面是完整可运行的实现代码:
HTML结构
<div class="input-group mb-3"> <input type="password" class="form-control" id="passwordInput" placeholder="输入密码"> <span class="input-group-text" id="togglePassword"> <i class="bi bi-eye"></i> <!-- 用Bootstrap Icons,换成Font Awesome的图标也可 --> </span> </div>
JavaScript逻辑
const togglePassword = document.getElementById('togglePassword'); const passwordInput = document.getElementById('passwordInput'); togglePassword.addEventListener('click', function () { // 切换密码输入框的type属性 const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password'; passwordInput.setAttribute('type', type); // 切换显示的图标 const icon = this.querySelector('i'); icon.classList.toggle('bi-eye'); icon.classList.toggle('bi-eye-slash'); }); // 给图标添加鼠标指针样式,提升交互体验 togglePassword.style.cursor = 'pointer';
你之前的方案出问题的原因
- 用相对定位时,没把图标放在和输入框同层级的容器内,导致图标被挤到输入框外部;
- 用绝对定位时,没有给输入框的父元素设置
position: relative,图标会相对于整个页面定位,要么跑丢,要么被输入框的内容层覆盖。
input-group是Bootstrap专门为输入框附加元素设计的组件,会自动处理好元素的定位和布局,图标会固定在输入框右侧,点击区域完全可控,不用额外写复杂的定位样式。如果你的项目没引入Bootstrap Icons,换成Font Awesome的fa-eye/fa-eye-slash也一样能用,逻辑不变。
内容的提问来源于stack exchange,提问作者Andy
相关产品推荐
相关产品推荐

