【问题标题】:How to change an input from text to password and vice-versa?如何将输入从文本更改为密码,反之亦然?
【发布时间】:2011-10-27 15:38:38
【问题描述】:

如果你访问this site,你可以看到Senha输入的类型是text。但是当我输入一些东西时,它会变成Password。

当我点击它时,它会保留我的输入并将其类型保持为Password。

但是,如果没有文本并且我点击退出,它会恢复为 text。

您能解释一下我如何轻松实现这样的目标吗?从用户体验的角度来看,这非常好。

我正在使用最新版本的 jQuery。

【问题讨论】:

  • 我没有看到 UX 的优势。为什么空白文本输入比空白密码更好?
  • 在源代码中搜索“changeToPassword”。
  • @GregL:它不是空白的。它显示文本:“Senha”。访问该网站,从用户的角度了解它是如何工作的。
  • 这个问题似乎适用,并显示了这个问题和解决方法的一些陷阱:stackoverflow.com/questions/1544317/…

标签: jquery text input passwords


【解决方案1】:

最简单的方法是使用HTML5 placeholder text。但这在某些浏览器中应用于密码字段时可能会出现一些意外的渲染,甚至在 IE9 之前的 IE 中根本不起作用。所以为了跨浏览器的一致性,我会为它使用一个 jQuery 插件:

http://plugins.jquery.com/project/html5placeholder

那么你几乎不需要做任何事情。在您的 HTML 中,您将设置一个常规密码文本字段,但带有一个占位符,如下所示:

<input type="password" placeholder="Senha">

在javascript中(包含上面的jQuery插件后),你可以激活它:

$('input').placeholder();

但是,如果您想使用传统方法(或者如果上述方法由于某种原因对您不起作用),您可以根据需要将密码字段替换为纯文本字段。你会像这样设置你的 HTML,有一个可见的提示和隐藏的实际字段:

<input id="password-field" type="password" name="password" style="display: none;">
<input id="password-prompt" type="text" value="Senha">

然后,jquery 把它换掉:

// This makes the password field show up when you focus on the prompt,
// and changes focus to the password field
$('#password-prompt').focus(function() {
    $(this).hide();
    $('#password-field').show().focus();
});

// This makes the prompt re-appear when you lose focus on the password field,
// but only if it's still empty (if you typed anything in, it leaves it as is)
$('#password-field').blur(function() {
    if ($(this).val() == '') {
        $(this).hide();
        $('#password-prompt').show();
    }
});

【讨论】:

    【解决方案2】:

    浏览器安全性不允许您直接更改输入类型。但是,您可以使用 replaceWith 将输入替换为密码类型:

    $("#input1").replaceWith($("<input>").attr({ "type" : "password", "id" : "input1" }));
    

    经过测试,它确实有效。这是jsFiddle。

    【讨论】:

      【解决方案3】:

      以下内容在 iOS Safari 上对我有用:

      $(function() {
          $('#tb').keypress(function() {
              $(this).prop('type', 'password');
          }).blur(function() {
              if ($(this).val() === '')
                  $(this).prop('type', 'text');
          });
      });
      

      jsFiddle:http://jsfiddle.net/unwJh/5/

      它可以在其他浏览器中使用吗?

      【讨论】:

        【解决方案4】:

        需要替换元素,例如:

        http://jsfiddle.net/YEHFe/

        【讨论】:

          猜你喜欢
          • 2014-06-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-23
          • 1970-01-01
          • 2020-12-29
          • 2013-09-21
          • 1970-01-01
          相关资源
          最近更新 更多