输入水印(css和Jquery)

Ora*_*ice 13 css jquery

JS

$(document).ready(function () {
    $(":input[data-watermark]").each(function () {
        $(this).val($(this).attr("data-watermark"));
        $(this).bind('focus', function () {
            if ($(this).val() == $(this).attr("data-watermark")) $(this).val('');
        });
        $(this).bind('blur', function () {
            if ($(this).val() == '') $(this).val($(this).attr("data-watermark"));
            $(this).css('color','#a8a8a8');
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

HTML

<label>Name: </label>
<input class="input" type="text" name="name" maxlength="" data-watermark="My Name" />
Run Code Online (Sandbox Code Playgroud)

CSS

.input{
    width:190px;
    height:16px;
    padding-top:2px;
    padding-left:6px;
    color:#000;
    font-size: 0.688em;
    border:#8c9cad 1px solid;
}
Run Code Online (Sandbox Code Playgroud)

我想要解决的是,每当水印的输入值为文本颜色应为灰色(#a8a8a8)时.当值是用户写的东西时,颜色应该是黑色.

这是小提琴:http://jsfiddle.net/qGvAf/

thi*_*dot 23

您已经完成了"输入水印"所需的行为 - 它被称为placeholder属性.它适用于现代浏览器.

对于旧版浏览器,您应该使用jQuery插件placeholder为您模拟.

最后,要设置颜色,您需要类似于此的CSS:

.placeholder {
    color: #a8a8a8;
}
::-webkit-input-placeholder {
    color: #a8a8a8;
}
:-moz-placeholder {
    color: #a8a8a8;
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,你无法结合上述规则; 它不会起作用.


小智 8

$(document).ready(function () {
    $(":input[data-watermark]").each(function () {
        $(this).val($(this).attr("data-watermark"));
        $(this).css("color","#a8a8a8");
        $(this).bind("focus", function () {
            if ($(this).val() == $(this).attr("data-watermark")) $(this).val('');
            $(this).css("color","#000000");
        });
        $(this).bind("blur", function () {
            if ($(this).val() == '') 
            {
                $(this).val($(this).attr("data-watermark"));
                $(this).css("color","#a8a8a8");
            }
            else
            {
                $(this).css("color","#000000");
            }
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 应该发布你发布代码块时所做的解释 (3认同)