textarea jQuery上的默认文本?

我有一个textarea,我想在页面加载时显示一些默认文本。 单击textarea后,我希望文本消失,如果用户在textarea中单击并且没有输入任何内容然后单击textarea,则默认文本将再次显示。

我已经搜索过谷歌并且在这里,但我似乎只能找到与文本框相关的教程而不是 textareas,而且我已经在textarea上使用了一个类,所以不能依赖于类来工作。

有没有人有一些简单的jQuery代码,他们想与我分享,以做我想要的上面?

演示: http //jsfiddle.net/marcuswhybrow/eJP9C/2/

重要的是要记住用户键入默认值的边缘情况。 我的解决方案通过使用jQuery的data()方法为每个textarea一个已edited标志来避免这种情况。

HTML

像往常一样定义textarea的默认值:

  

jQuery

 $('textarea').each(function() { // Stores the default value for each textarea within each textarea $.data(this, 'default', this.value); }).focus(function() { // If the user has NOT edited the text clear it when they gain focus if (!$.data(this, 'edited')) { this.value = ""; } }).change(function() { // Fires on blur if the content has been changed by the user $.data(this, 'edited', this.value != ""); }).blur(function() { // Put the default text back in the textarea if its not been edited if (!$.data(this, 'edited')) { this.value = $.data(this, 'default'); } }); 

演示: http //jsfiddle.net/marcuswhybrow/eJP9C/2/

很简单:

 $(function() { $('textarea.autoDefault').focus(function() { if($(this).val() === $(this).data('default') && !$(this).data('edited')) { $(this).val(''); } }).change(function() { $(this).data('edited', this.value.length > 0); }).blur(function() { if($(this).val().length === 0) { $(this).val($(this).data('default')); } }).blur(); //fire blur event initially }); 

HTML标记:

  

jsFiddle示例

 "style='color:#888;' onfocus='inputFocus(this)' onblur='inputBlur(this)'" 

^将其添加到HTML元素中

 function inputFocus(i){ if(i.value==i.defaultValue){ i.value=""; i.style.color="#000"; } } function inputBlur(i){ if(i.value==""){ i.value=i.defaultValue; i.style.color="#888"; } } 

^将其添加到document.ready函数中

我刚才在SO上找到了这个解决方案而且我还没有看到它做得更好

我搜索过Google并在这里,但我似乎只能找到与文本框相关的教程

无论在文本框中使用什么,也可以在jQuery中的textarea上使用。 val()方法检测使用的控件,并将使用value属性作为textarea的输入和内部文本

拿起任何这些链接并实现它

另一种方法是使用HTML5的占位符标记。

http://davidwalsh.name/html5-placeholder

这可能不是所有浏览器都支持,特别是旧的IE。