【问题标题】:Jquery default value in password field密码字段中的Jquery默认值
【发布时间】:2011-08-21 21:53:30
【问题描述】:

我正在使用this Jquery plugin 来填充输入,其中包含在单击时消失的文本。它不适合密码字段,因为所有内容都显示为点。在您开始输入之前,让默认文本在密码字段中可见的好方法是什么?

【问题讨论】:

    标签: javascript jquery html forms input


    【解决方案1】:

    如建议的那样,您可以交换输入,但它在 IE 中不起作用。 IE 不允许这样做,因为它可能是某种安全漏洞。

    我以前用这个:

    /* From: http://grzegorz.frydrychowicz.net/jquery_toggleformtext/
       Modified to swap password textbox type so watermark can be read */
    $(document).ready(function() {
        if (!jQuery.browser.msie) {
            $("input:password").each(function() {
                if (this.value == '') {
                    this.type = "text";
                }
                $(this).focus(function() {
                    this.type = "password";
                });
                $(this).blur(function() {
                    if (this.value == '') {
                        this.type = "text";
                    }
                });
            });
        }
        $("input:text, textarea, input:password").each(function() {
            if (this.value == '') {
                $(this).addClass("watermark");
                this.value = this.title;
            }
        });
        $("input:text, textarea, input:password").focus(function() {
            $(this).removeClass("watermark");
            if (this.value == this.title) {
                this.value = '';
            }
        });
        $("input:text, textarea, input:password").blur(function() {
            if (this.value == '') {
                $(this).addClass("watermark");
                this.value = this.title;
            }
        });
        $("input:image, input:button, input:submit").click(function() {
            $(this.form.elements).each(function() {
                if (this.type == 'text' || this.type == 'textarea' || this.type == 'password') {
                    if (this.value == this.title && this.title != '') {
                        this.value = '';
                    }
                }
            });
        });
    });
    

    我终于放弃了正常的密码输入行为。我发现上面的输入交换有点古怪,但你可以试一试。

    【讨论】:

    • 好脚本!要解决 IE,如何使用 show() 和 hide() 隐藏 type=text on click 和 show(0 type=password fields?
    【解决方案2】:

    通过 JS,我的答案将与 @ultimatebuster 的相同。然而,整个 JS 路线是 hacky,现在替代品开始出现。现在很多现代浏览器直接通过 HTML5 支持这个东西:

    <input type="password" name="password" placeholder="Enter password"/>
    

    (许多现代浏览器 = 除了 Internet Explorer 之外的所有主要浏览器。我拒绝为它编写代码;如果您必须在 IE 中也有相同的东西,那么您将不得不走 hacky 路线。)

    【讨论】:

    • placeholder 太棒了!我为你放弃 Explorer 鼓掌。
    【解决方案3】:

    您可以将输入字段的类型设置为密码。但是,在页面加载时通过 javascript 将其设置为正常(这样,如果用户没有 JS,您可以轻松地回退)。收到点击后,将输入字段的类型设置回密码。

    【讨论】:

      猜你喜欢
      • 2011-02-28
      • 2013-10-10
      • 2012-06-24
      • 1970-01-01
      • 2020-07-11
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 2012-03-29
      相关资源
      最近更新 更多