在密码输入字段中显示/隐藏图标切换

问题描述 投票:0回答:3

我有一个简单的 HTML 登录表单:

const passwordField = document.querySelector("#password");
const eyeIcon = document.querySelector("#eye");

eye.addEventListener("click", function() {
  this.classList.toggle("fa-eye-slash");
  const type = passwordField.getAttribute("type") === "password" ? "text" : "password";
  passwordField.setAttribute("type", type);
})
<script src="https://kit.fontawesome.com/6d0b0e6586.js" crossorigin="anonymous"></script>
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@200;400;500;600&display=swap" rel="stylesheet">
<div id="login-flow">
  <section>
    <h1>Welcome back.</h1>
    <form action="#" method="post">
      <label for="email">Email</label>
      <input type="email" id="email" name="email" placeholder="Email" required>
      <label for="password">Password</label>
      <div class="password-container">
        <input type="password" name="password" id="password" placeholder="Password" required>
        <i class="fa-solid fa-eye" id="eye"></i>
      </div>
      <!--pass-toggle-->
      <button type="button" name="btn" id="btn-login">Login</button>
    </form>
    <div class="form-footer">
      <p>Don't have an account? Create one <a href="register.html">here</a>.</p>
    </div>
  </section>
</div><!--login-flow-->

一切都很好除了图标切换。没有警告,密码输入字段在控制台中的密码和文本之间变化,但图标没有变化。有趣的是,如果我将 fa-eye-slash

 类添加到 
<i>
 中的 
.password-container
,并将 
this.classList.toggle
 添加到 
fa-eye
,它会完美地工作。只是图标颠倒了而已。为什么它不能按原样工作?

javascript html forms show-hide
3个回答
0
投票
您将事件侦听器附加到不存在的变量。试试这个

eyeIcon.addEventListener("click", function() { this.classList.toggle("fa-eye-slash"); const type = passwordField.getAttribute("type") === "password" ? "text" : "password"; passwordField.setAttribute("type", type); })
    

0
投票
这是您的解决方案

eye.addEventListener("click", function() { const type = passwordField.getAttribute("type") === "password" ? "text" : "password"; passwordField.setAttribute("type", type); if (passwordField.getAttribute("type") === "password") { eyeIcon.classList.remove("fa fa-eye"); eyeIcon.classList.add("fa fa-eye-slash"); } else { eyeIcon.classList.remove("fa fa-eye-slash"); eyeIcon.classList.add("fa fa-eye"); } })
    

0
投票
我没有足够的声誉来发表评论,但只是想说,我在同一条船上,使用相同的代码关注相同的视频。这里提供的所有回复均无效。

我更好奇讨论是如何进行的,@Thistlefinch

© www.soinside.com 2019 - 2024. All rights reserved.