我有一個簡單的 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>in.password-container和this.classList.toggleto 中fa-eye,它會完美運行。只是圖示顛倒了。為什么它不能按原樣作業?
uj5u.com熱心網友回復:
您將事件偵聽器附加到一個不存在的變數。嘗試這個
eyeIcon.addEventListener("click", function() {
this.classList.toggle("fa-eye-slash");
const type = passwordField.getAttribute("type") === "password" ? "text" : "password";
passwordField.setAttribute("type", type);
})
uj5u.com熱心網友回復:
這是你的解決方案
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");
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/524378.html
