javascript - jQuery 文本区域上的默认文本?

标签 javascript jquery textarea default

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

我已经在Google和这里搜索过,但我似乎只能找到与文本框和不能文本区域相关的教程,而且我已经在文本区域上使用了一个类,所以不能依赖于它的类去工作。

有人愿意与我分享一些简单的 jQuery 代码来完成我上面想要的事情吗?

最佳答案

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

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

HTML

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

<textarea>This is the default text</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/

关于javascript - jQuery 文本区域上的默认文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4771794/

相关文章:

html - &lt;textarea&gt; 中可以包含多行 HTML5 占位符文本吗?

javascript - 后台选项卡中的 setTimeout/setInterval 1000 毫秒延迟(Chrome 和 Firefox)

javascript - WebView .reload() 在 iOS 上无法正常工作

javascript - 如何从 rc-slider react 组件输出当前值?

javascript - 使用 jQuery 在 textarea 中插入脚本标签

php - 如何更改 nicedit 默认颜色

javascript - 删除 ajax 加载的内容和脚本

javascript - jquery ajax不起作用(服务器端是ASP.net)

jquery - 写入非唯一 div 的唯一属性

javascript - jQuery 平滑改变 innerHTML