簡體   English   中英

textarea jQuery上的默認文本?

[英]Default text on textarea jQuery?

我有一個textarea,我想在頁面加載時顯示一些默認文本。 單擊textarea后,我希望文本消失,如果用戶在textarea中單擊並且沒有輸入任何內容然后單擊textarea,則默認文本將再次顯示。

我已經搜索過谷歌並且在這里,但我似乎只能找到與文本框相關的教程而不是 textareas,而且我已經在textarea上使用了一個類,所以不能依賴於類來工作。

有沒有人有一些簡單的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/

很簡單:

$(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標記:

<textarea class="autoDefault" rows="10" cols="25" data-default="some default text"></textarea>

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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM