2011-06-17 101 views
0

我有一個表單輸入,其中包含示例搜索關鍵字。jQuery:用戶開始輸入後更改輸入值顏色

當用戶關注輸入時,文本消失,如果輸入中沒有任何內容,文本在未聚焦時會重新出現。

這一切都很好,效果很好,但我想要做的是將示例文本變爲灰色,然後在用戶實際輸入時具有正常的純色。

以下是我目前使用的代碼。任何幫助將是偉大的!

$(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'); 
    } 
}); 
}); 

回答

4

喜歡這個?

$(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"); 
     } 
    }); 
}); 

http://jsfiddle.net/afcpb/

只需設置每當重點和回來,如果默認的文本再次被設置爲灰色它最初灰色,然後將黑色。

+0

這是完美的,謝謝。 –

1

有佔位= 「東西」 在HTML5屬性。所以你會說, < input type =「text」placeholder =「something」/ > 我認爲這是最好的答案,因爲Jquery不需要這樣做。