如何在密码字段中添加文本水印?

Sur*_*ine 4 html jquery

我想在我的密码字段中写一个水印,上面写着"密码".

这是我的代码:
jquery:

$(document).ready(function() {

    var watermark = 'Password';

    //init, set watermark text and class
    $('#input_pwd').val(watermark).addClass('watermark');

    //if blur and no value inside, set watermark text and class again.
    $('#input_pwd').blur(function(){
        if ($(this).val().length == 0){
            $(this).val(watermark).addClass('watermark');
        }
    });

    //if focus and text is watermrk, set it to empty and remove the watermark class
    $('#input_pwd').focus(function(){
        if ($(this).val() == watermark){
            $(this).val('').removeClass('watermark');
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

HTML:

<input class="ui_input" id="input_pwd" type="password" name="pass" id="pass" style="height:25px; width:250px; font-size:14px;" required />
Run Code Online (Sandbox Code Playgroud)

我的jsfiddle: 点击这里


编辑:我更喜欢jquery :)

编辑:我们的兄弟Konrad Gadzina给了我正在寻找的东西,但感谢大家的所有努力!

Kon*_*ina 8

您可以将默认设置为type,text并password在删除watermark类时将其更改为JS .

HTML:

<input class="ui_input" id="input_pwd" type="text" name="pass" id="pass" style="height:25px; width:250px; font-size:14px;" required />
Run Code Online (Sandbox Code Playgroud)

JS:

    //if blur and no value inside, set watermark text and class again.
    $('#input_pwd').blur(function(){
        if ($(this).val().length == 0){
            $(this).val(watermark).addClass('watermark');
            $(this).attr('type', 'text');
        }
    });

    //if focus and text is watermrk, set it to empty and remove the watermark class
    $('#input_pwd').focus(function(){
        if ($(this).val() == watermark){
            $(this).val('').removeClass('watermark');
            $(this).attr('type', 'password');
        }
    });
Run Code Online (Sandbox Code Playgroud)

检查小提琴 - http://jsfiddle.net/w4Hh4/1/


Spo*_*key 5

使用html placeholder

<input class="ui_input" id="input_pwd" type="password" name="pass" id="pass" style="height:25px; width:250px; font-size:14px;" placeholder='Password' required />
Run Code Online (Sandbox Code Playgroud)

你不需要任何js.

注意:Internet Explorer 10,Firefox,Opera,Chrome和Safari支持占位符属性.不幸的是,评论中指出它不适用于旧IE