根据文本中包含的文本数量扩展textarea(jquery)

use*_*974 6 css jquery textarea

我怎样才能让textarea最初只有1行,但是当文本到达行尾时添加另一行,并继续这样做直到最多5行?

Jak*_*sel 1

像这样的东西:

<textarea id="foo" rows="1" cols="40"></textarea>

$(function () {

    $("#foo").on("keyup", function () {

       if ($(this).attr('rows') < 5 &&
           parseInt($(this).val().length/$(this).attr('cols')) >= $(this).attr('rows'))
           $(this).attr("rows", parseInt($(this).attr("rows"))+1);

    });

});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/Q3pPT/

编辑处理换行符的轻微改进:

$(function () {

    $("#foo").on("keyup", function (e) {

       if ($(this).attr('rows') < 5)
       {
           if (
               parseInt($(this).val().length/$(this).attr('cols'))+
               ($(this).val().split("\n").length-1) 

               >= 

               $(this).attr('rows')
              )
               $(this).attr("rows", parseInt($(this).attr("rows"))+1);

           if (e.keyCode == 13)
           {
               $(this).attr("rows", parseInt($(this).attr("rows"))+1);
           }
       } 

    });

});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/Q3pPT/2/