如何仅单击并显示密码?

时间:2020-02-08 10:26:55

标签: jquery html

我有一个密码字段,我想在有人单击眼睛图标时显示密码 ,而当鼠标离开时我想再次屏蔽密码。该怎么做?

我找到了以下代码,但在这种情况下,悬停事件需要点击并按住

$('.icon').hover(function () {
   $('.password').attr('type', 'text'); 
}, function () {
   $('.password').attr('type', 'password'); 
});
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="password" class="password" type="password" />
<div class="fa fa-eye icon"></div>

5 个答案:

答案 0 :(得分:2)

$('.icon').mousedown(function () {
   $('.password').attr('type', 'text'); 
});
$('.icon').mouseup(function () {
   $('.password').attr('type', 'password'); 
});
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="password" class="password" type="password" />
<div class="fa fa-eye icon"></div>

答案 1 :(得分:0)

$('.icon').click(function () {
   if ($('.password').attr('type') == 'text') {
      $('.password').attr('type', 'password');
   } else {
      $('.password').attr('type', 'text');
   }
});
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="password" class="password" type="password" />
<div class="fa fa-eye icon"></div>

答案 2 :(得分:0)

经过测试!

 $('.icon').click(function () {
    $('.password').attr('type', 'text');
    setTimeout(function(){ 
        $('.password').attr('type', 'password');
    }, 200); 
}); 
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="password" class="password" type="password" />
<div class="fa fa-eye icon"></div>

答案 3 :(得分:0)

尝试使用(ajax.googleapis.com/ajax/libs/jquery)

$('.icon').hover(function () {
   $('.password').attr('type', 'text'); 
}, function () {
   $('.password').attr('type', 'password'); 
});

答案 4 :(得分:0)

使用此代码,您可以添加用于显示和隐藏密码的按钮,也可以在更改状态(显示密码/隐藏密码)后更改按钮。

$('.icon').click(function () {
   if ($('#my-password').attr('type') == 'text') {
      $('#my-password').attr('type', 'password');
      $('#show-password').removeClass('fa-eye-slash').addClass('fa-eye');
   } else {
      $('#my-password').attr('type', 'text');
      $('#show-password').removeClass('fa-eye').addClass('fa-eye-slash');
   }
});
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="password" id="my-password" type="password" />
<div class="fa fa-eye icon" id="show-password"></div>

我使用ID属性选择密码输入和按钮。