如何切换按钮内的图标?密码显示切换代码求助
解决密码框切换时同步切换Font Awesome图标的问题
你的代码已经实现了密码输入框和文本输入框的类型切换,但按钮内的Font Awesome图标未同步变化,这是因为代码仅处理了输入框的类型修改,没有对图标的类名进行切换操作。以下是修改后的完整代码,解决图标同步切换的问题:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:p="http://primefaces.org/ui"> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/> <style> #togglePassword{ margin-left: -5px; margin-top: 11px; cursor: pointer; } </style> </head> <body> <p:inputText id="productadminpassword" value="password" type="password"> </p:inputText> <button type="button" onclick="showHide();" > <i class='fa fa-eye-slash' id="eye" /> </button> <script type="text/javascript"> function showHide() { const passwordInput = document.getElementById('productadminpassword'); const eyeIcon = document.getElementById('eye'); if (passwordInput.type == "password") { passwordInput.type = 'text'; eyeIcon.classList.remove('fa-eye-slash'); eyeIcon.classList.add('fa-eye'); } else { passwordInput.type = 'password'; eyeIcon.classList.remove('fa-eye'); eyeIcon.classList.add('fa-eye-slash'); } }; </script> </body> </html>
关键修改说明:
- 通过
document.getElementById获取输入框和图标元素,避免直接使用全局id变量,代码更规范且不易出错。 - 在切换输入框类型的同时,使用
classList.remove()和classList.add()方法,精准切换图标的Font Awesome类名:- 当输入框从密码类型切换为文本类型时,移除
fa-eye-slash类并添加fa-eye类 - 当输入框从文本类型切换回密码类型时,移除
fa-eye类并添加fa-eye-slash类
- 当输入框从密码类型切换为文本类型时,移除
这样就能实现输入框类型与图标状态的同步切换了。
内容的提问来源于stack exchange,提问作者New User
相关产品推荐
相关产品推荐

