2012-04-12 63 views
0

我有一個textarea默認的列數,如10或15或什麼的。我希望文本區域在模糊處縮小內部文本。有誰知道如何做到這一點?jquery如何根據內容減少文本區cols的數量

到目前爲止,我有

$('textarea').live('blur', function() { 
    var textAreaWidth = $(this).val().length; 
    $(this).attr('cols', 'textAreaWidth'); 

}); 

但這是醜陋的原因是顯而易見的。我只是不知道如何做到這一點。

什麼想法?

回答

1

如果您只想減小尺寸,則應檢查該值是否小於20,然後減少列數。試試這個:

<textarea rows="2" cols="20"></textarea> 

$('textarea').on('blur', function() { 
    var textAreaWidth = $(this).val().length; 

    if (textAreaWidth < 20) { 
     $(this).attr('cols', textAreaWidth); 
    } 
    $('textarea').on('keypress', function() { 
     $(this).attr('cols', '20'); 
    }); 
}); 

http://jsfiddle.net/4bccm/

+0

好主意添加if語句,我在想,但原始問題仍然存在。就像我放入1個字符一樣,文本框實際上會變得更長。 Idk發生了什麼事 – mharris7190 2012-04-12 06:36:26

2

$(this).attr('cols', 'textAreaWidth');

刪除從各地「textAreaWidth」單引號這是一個變量,並不需要周圍的引號。

0
$('textarea').bind('blur keyup', function() { 
    $(this).attr('cols', $(this).val().length); 
});​ 

這使得收縮或增長,因爲你鍵入/模糊。