Javascript jquery如何根据内容减少textarea中的列数

Javascript jquery如何根据内容减少textarea中的列数,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我有一个默认列数的textarea,比如10或15之类的。我希望文本区域在模糊时收缩包裹文本。有人知道怎么做吗 到目前为止我有 $('textarea').live('blur', function() { var textAreaWidth = $(this).val().length; $(this).attr('cols', 'textAreaWidth'); }); 但这是丑陋的,原因显而易见。我只是不知道怎么做 有什么想法吗?删除中“textAreaWidth”左右

我有一个默认列数的textarea,比如10或15之类的。我希望文本区域在模糊时收缩包裹文本。有人知道怎么做吗

到目前为止我有

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

});
但这是丑陋的,原因显而易见。我只是不知道怎么做


有什么想法吗?

删除中“textAreaWidth”左右的单引号

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


这是一个变量,不需要在其周围加引号。

从中的“textAreaWidth”周围删除单引号

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


这是一个变量,不需要在其周围加引号。

如果只想减小大小,则应检查该值是否小于,例如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');
    });   
});

$('textarea')。在('blur',function()上{
var textAreaWidth=$(this).val().length;
如果(文本区域宽度<20){
$(this.attr('cols',textAreaWidth);
}
$('textarea')。在('keypress',function()上{
$(this.attr('cols','20');
});   
});

如果只想减小大小,则应检查值是否小于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');
    });   
});

$('textarea')。在('blur',function()上{
var textAreaWidth=$(this).val().length;
如果(文本区域宽度<20){
$(this.attr('cols',textAreaWidth);
}
$('textarea')。在('keypress',function()上{
$(this.attr('cols','20');
});   
});

这会使其在键入/模糊时收缩或增长


这会使它在键入/模糊时缩小或增大。

添加if语句是个好主意,我已经考虑过了,但是原始问题仍然存在。如果我输入一个字符,文本框实际上会变长。Idk What’s good idea添加if语句是个好主意,我正在考虑,但是原始问题仍然存在。如果我输入一个字符,文本框实际上会变长。Idk发生什么事了