如何在密码输入框内添加Font Awesome图标实现密码显隐切换
密码输入框内置Font Awesome显隐切换图标实现
你现有代码不生效的核心问题有3个:
- 眼睛图标节点放在了密码输入框的父容器外部,无法和输入框形成定位关联
- 输入框容器没有设置相对定位,图标也没有设置绝对定位,没法把图标固定在输入框内侧末尾位置
- 缺少点击图标切换密码显隐状态、切换图标样式的交互逻辑
修正后完整实现
样式调整
首先给输入框包裹容器加相对定位作为定位参照,给输入框加足够的右侧内边距避免输入内容被图标遮挡,再把图标固定到输入框右侧内部:
.regform{ display: inline-block; align-items: center; width: 80%; } /* 输入框容器设为相对定位,作为图标定位的父参照 */ .input { position: relative; } input[type=text], input[type=password], input[type=email] { padding: 8px 40px 8px 8px; /* 右侧预留图标位置 */ width: 90%; margin-bottom: 22px; font-size: 16px; border-radius: 500px; border: 2px solid #43969A; box-sizing: border-box; } input::placeholder { color: #074B78; } /* 固定图标到输入框右侧内部 */ .input i { position: absolute; right: 12%; top: 35%; transform: translateY(-50%); cursor: pointer; color: #43969A; } button { background-color: #B2D235; border: none; border-radius: 500px; width: 100%; padding: 10px 100px; font-size: 16px; color: #074B78; text-transform: uppercase; white-space: nowrap; cursor: pointer; }
结构调整
把原来放在密码框容器外面的眼睛图标移到密码输入框对应的.input容器内部,给图标加id方便绑定事件:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <div class="regform"> <form action=""> <div class="input"> <input type="text" placeholder="Naam" required> </div> <div class="input"> <input type="email" placeholder="E-mail" name="email" id="email" required> </div> <div class="input"> <input type="password" placeholder="Password" name="psw" id="psw" required> <i class="fa-solid fa-eye-slash" id="togglePwd"></i> </div> <button type="submit" class="registerbtn">Meld je aan</button> </form> </div>
交互逻辑
添加点击事件,点击图标时切换输入框的type属性,同时切换图标类名匹配当前显隐状态:
const togglePwdBtn = document.getElementById('togglePwd'); const pwdInput = document.getElementById('psw'); togglePwdBtn.addEventListener('click', () => { const isPasswordHidden = pwdInput.type === 'password'; // 切换输入框显隐 pwdInput.type = isPasswordHidden ? 'text' : 'password'; // 切换对应图标 togglePwdBtn.classList.toggle('fa-eye-slash', !isPasswordHidden); togglePwdBtn.classList.toggle('fa-eye', isPasswordHidden); })
实现效果
- 图标固定在密码输入框内侧右端,不会随页面布局、输入内容移位
- 输入框右侧预留了足够的内边距,输入的密码文字不会被图标遮挡
- 点击图标即可在密文/明文显示之间切换,图标样式同步更新
- 鼠标悬浮到图标上会显示手型,明确可点击交互
内容的提问来源于stack exchange,提问作者Milan
相关产品推荐
相关产品推荐

