无法切换密码框眼睛与斜杠眼睛图标类,请求修复代码
密码显示/隐藏图标切换修复方案
问题出在两个核心点:
- 箭头函数没有独立的
this上下文,导致this.classList.toggle('bi-eye')无法正确指向图标元素 - 仅切换了
bi-eye类,未处理初始的bi-eye-slash类,无法完成图标双向切换
以下是修复后的完整可运行代码:
<p> <label>Password:</label> <input type="password" name="password" id="password" /> <i class="bi bi-eye-slash" id="togglePassword"></i> </p> <script> 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); // 双向切换eye和eye-slash图标类 this.classList.toggle('bi-eye'); this.classList.toggle('bi-eye-slash'); }); </script>
修改说明:
- 替换箭头函数为普通函数:普通函数中的
this会自动指向触发点击事件的图标元素(togglePassword),确保类操作能正确作用到目标元素上 - 同时切换两个图标类:初始图标带有
bi-eye-slash类,点击时同时切换bi-eye和bi-eye-slash,实现显示/隐藏状态下的图标双向切换
内容的提问来源于stack exchange,提问作者Selvakumar Ravichandiran
相关产品推荐
相关产品推荐

