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

无法切换密码框眼睛与斜杠眼睛图标类,请求修复代码

密码显示/隐藏图标切换修复方案

问题出在两个核心点:

  • 箭头函数没有独立的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>

修改说明:

  1. 替换箭头函数为普通函数:普通函数中的this会自动指向触发点击事件的图标元素(togglePassword),确保类操作能正确作用到目标元素上
  2. 同时切换两个图标类:初始图标带有bi-eye-slash类,点击时同时切换bi-eye和bi-eye-slash,实现显示/隐藏状态下的图标双向切换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 05:50:11