为啥隐藏和显示密码功能无法正常工作?
Posted
技术标签:
【中文标题】为啥隐藏和显示密码功能无法正常工作?【英文标题】:Why is Hide and Show password feature not working in form?为什么隐藏和显示密码功能无法正常工作? 【发布时间】:2021-10-07 21:28:56 【问题描述】:我只是想在我的登录表单中添加一个显示密码的功能。我尝试了几种方法,但仍然无法正常工作。我不明白为什么会这样。谁能帮帮我?
$(".toggle-password").click(function()
$(this).toggleClass("fa-eye fa-eye-slash");
var input = $($(this).attr("toggle"));
if (input.attr("type") == "password")
input.attr("type", "text");
else
input.attr("type", "password");
);
/**function showPwd(id, el)
let x = document.getElementById(id);
if (x.type === "password")
x.type = "text";
el.className = 'fas fa-eye-slash toggle-password';
else
x.type = "password";
el.className = 'fas fa-eye toggle-password';
**/
/**const togglePassword = document.querySelector('.toggle-password');
const password = document.querySelector('#password-field');
togglePassword.addEventListener('click', function (e)
// toggle the type attribute
const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
password.setAttribute('type', type);
// toggle the eye / eye slash icon
this.classList.toggle('fa-eye');
);**/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="post">
<input id="password-field" type="password" name="Password" value="Password" onfocus="this.value = '';" onblur="if (this.value == '') this.value = 'Password';" required="***" />
<span toggle="#password-field" class="fas fa-eye-slash fa-eye field-icon toggle-password
hidepass">
</span>
</form>
我也尝试了两种不同的方法,我在脚本中注释了它以使其工作,但这些也不起作用。请有人帮忙。here is the image
【问题讨论】:
嗨,Emon,你能用你的代码创建一个游乐场来测试它吗? 【参考方案1】:切换主类会删除单击它的能力,因此添加一个使用opacity
隐藏它的类,使其仍可单击。
$(".toggle-password").click(function()
$(this).toggleClass("hidden");
var input = $($(this).attr("toggle"));
if (input.attr("type") == "password")
input.attr("type", "text");
else
input.attr("type", "password");
);
.hidden
opacity: 0.2;
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="post">
<input id="password-field" type="password" name="Password" value="Password" onfocus="this.value = '';" onblur="if (this.value == '') this.value = 'Password';" required="***" />
<span toggle="#password-field" class="fas fa-eye-slash fa-eye field-icon toggle-password
hidepass">
</span>
</form>
【讨论】:
我已经复制了你的脚本代码和.hidden css。但它仍然无法正常工作......以上是关于为啥隐藏和显示密码功能无法正常工作?的主要内容,如果未能解决你的问题,请参考以下文章