KB_*_*yan 2 html javascript jquery
我正在尝试创建一个密码字段,允许用户单击眼睛图标来查看或隐藏其密码。然而,除此之外,我想当用户单击字段外部时自动隐藏密码。这需要点击和模糊事件。问题是模糊事件在单击事件之前运行,并在我单击眼睛图标时运行。这会导致该字段切换两次,因为它在模糊事件块中运行,然后在单击事件块中运行。
我基本上需要它来允许我通过单击眼睛图标进行切换,并在退出字段时将字段设置回密码类型。我尝试使用 onmousedown 但它的行为非常奇怪,它仅在我单步执行开发工具时才有效。
function togglePassword(element) {
$(element).toggleClass("fa-eye fa-eye-slash");
$(element).siblings("input").each(function() {
if ($(element).hasClass('fa-eye-slash')) {
$(this).attr('type', 'text');
$(this).focus();
} else if ($(element).hasClass('fa-eye')) {
$(this).attr('type', 'password');
}
});
}
function toggleWhenExiting(element) {
console.log("focus toggle");
$(element).siblings("span").each(function() {
if ($(this).hasClass('fa-eye-slash')) {
$(element).attr('type', 'password');
$(this).toggleClass("fa-eye fa-eye-slash");
}
});
}Run Code Online (Sandbox Code Playgroud)
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<input type="password" id="passwordFirst" class="form-control" onblur="toggleWhenExiting(this)">
<span class="fas fa-eye" id="togglePassword" onclick="togglePassword(this)"></span>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)
我们可以通过使用两个元素的常量并使用 jQuery 的one()方法创建仅触发一次的事件处理程序来简化和澄清事情。请注意,我已从标记中删除了所有事件处理程序,以实现关注点分离的现代化。
我们还可以检查模糊状态,并且仅在不是切换按钮relatedTarget时才采取操作。请注意,我已添加到该元素以使其可聚焦。如果没有它,它就不会被报告为模糊目标。tabindex="0"
$('#togglePassword').click(function() {
const eyeIcon = $(this);
const pwdInput = $('#passwordFirst');
pwdInput.off('blur');
if (eyeIcon.hasClass('fa-eye')) {
eyeIcon.removeClass('fa-eye').addClass('fa-eye-slash');
pwdInput.attr('type', 'text').focus();
pwdInput.one('blur', function(e) {
if ($(e.relatedTarget).attr('id') !== 'togglePassword') {
pwdInput.attr('type', 'password');
eyeIcon.removeClass("fa-eye-slash").addClass('fa-eye');
}
});
} else {
eyeIcon.removeClass('fa-eye-slash').addClass('fa-eye');
pwdInput.attr('type', 'password');
}
});Run Code Online (Sandbox Code Playgroud)
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<input type="password" id="passwordFirst" class="form-control">
<span class="fas fa-eye" id="togglePassword" tabindex="0"></span>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)