【问题标题】:Revealing input type="password"显示输入类型=“密码”
【发布时间】:2015-06-21 23:22:33
【问题描述】:

我正在尝试制作一个按钮来显示输入上写的密码。 我可怜的 JS 技能告诉我,我可以通过这样做来实现它:

我试过了:

$('#passReveal').on('click', function(){
    $( "#input-show" ).attr('type', 'text');
    if ($( "#input-show" ).attr('type', 'text')){
        $( "#input-show" ).attr('type', 'password');
    }
});

但不起作用。

我认为这是最接近的,但我有一个错误:您必须单击两次按钮才能使其第一次工作,这是为什么呢?

$('#passReveal').on('click', function(){
    $( "#input-show" ).attr('type', 'text');
    $( "#input-show" ).toggleClass('passRevealed');
    if ($( "#input-show" ).hasClass('passRevealed')){  
        $( "#input-show" ).attr('type', 'password');        
    }
});

https://jsfiddle.net/tepLkc7u/2/

我希望你能理解我糟糕的英语,我正在学习:)

【问题讨论】:

  • 你的逻辑正好相反。你使用的是.attr('type', 'passowrd'),而它应该是.attr('type', 'text')

标签: jquery passwords


【解决方案1】:

您无法跨浏览器可靠地更改 inputtype

您可以做的是将两个输入并排放置,然后选择显示哪一个:

$('#passReveal').on('click', function() {
  var show = $("#input-show"),
      pass = $("#input-pass"),
      showing = show.is(":visible"),
      from = showing ? show : pass,
      to = showing ? pass : show;
  from.hide();
  to.val(from.val()).show();
  $(this).text(showing ? "Reveal" : "Hide");
});
<input type="password" id="input-pass" placeholder="Password">
<input type="text" id="input-show" placeholder="Password" style="display: none">
<button id="passReveal">Reveal</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

【讨论】:

  • 太棒了!在 then 块中使用 $(this).text('Reveal') 并在 else 块中使用 $(this).text('Hide') 会使这个 完美
  • @PeterKA:啊,好点子。 :-) 我也不喜欢重复的代码,但每次我尝试改进它时,它都变得更糟而不是更好。不过,我想我最终改进了它。
【解决方案2】:

您所做的是切换类,然后将输入类型设置为密码(如果有类)。

所以,因为它第一次有这个类(它被切换进来),它会使输入类型恢复为密码。

第二次,它不会因为输入不再有类。

尽管如此,第一次尝试使其工作

$('#passReveal').on('click', function() {
  $("#input-show").attr('type', 'text');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input type="password" id="input-show" placeholder="Password">
<button id="passReveal">Reveal</button>

更新

如果您希望实现 IE 兼容性,请注意动态更改 type 属性。相反,请遵循使用两个单独输入的方法,如 @T.J.人群回答。

请参阅Changing <input> type using jQuery with cross browser supportattr() 中有关跨浏览器一致性的注释

【讨论】:

  • 您无法可靠地更改现有 input 的跨浏览器 type
  • @T.J.Crowder,不要说跨浏览器。这是关于 IE 兼容性(翻白眼)。感谢stackoverflow.com/questions/5881874/… 中的好回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-28
  • 2019-04-23
  • 2011-04-29
  • 2015-01-30
  • 2018-04-23
相关资源
最近更新 更多