您将事件侦听器附加到一个不存在的变量。试试这个
我有一个简单的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
类添加到.password-container
中的<i>
,并将this.classList.toggle
添加到fa-eye
,它就可以完美地工作。只是图标颠倒了。为什么它不能正常工作?
eyeIcon.addEventListener("click", function() {
this.classList.toggle("fa-eye-slash");
const type = passwordField.getAttribute("type") === "password" ? "text" : "password";
passwordField.setAttribute("type", type);
})
这是您的解决方案
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");
}
})