jQuery:用户开始输入后更改输入值颜色

Cla*_*n C 0 forms jquery input

我有一个表单输入,其中包含示例搜索关键字.

当用户聚焦输入时,文本消失,如果输入中没有任何内容,则在未聚焦时文本会重新出现.

这一切都很好并且效果很好,但我想做的是让示例文本变灰,然后在用户实际打字时使用正常的纯色.

以下是我目前使用的代码.任何帮助都会很棒!

$(function() {
$('input').each(function() {
    $.data(this, 'default', this.value);
}).focus(function() {
    if (!$.data(this, 'edited')) {
        this.value = "";
    }
}).change(function() {
    $.data(this, 'edited', this.value != "");
}).blur(function() {
    if (!$.data(this, 'edited')) {
        this.value = $.data(this, 'default');
    }
});
});
Run Code Online (Sandbox Code Playgroud)

Jam*_*gne 5

像这样?

$(function() {
    $('input').each(function() {
        $.data(this, 'default', this.value);
    }).css("color","gray")
    .focus(function() {
        if (!$.data(this, 'edited')) {
            this.value = "";
            $(this).css("color","black");
        }
    }).change(function() {
        $.data(this, 'edited', this.value != "");
    }).blur(function() {
        if (!$.data(this, 'edited')) {
            this.value = $.data(this, 'default');
            $(this).css("color","gray");
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/afcpb/

只需将其初始设置为灰色,然后在聚焦时将其设置为黑色,如果再次设置默认文本,则将其设置为灰色.