3

I use something like this, for auto growing (auto size) textarea:

$('textarea').keyup(function() {
    $(this).attr('rows', $(this).val().split("\n").length);
});

How to add smooth animation to auto growing for code above?

Function .animate() with rows doesn't work.

4

3 回答 3

2

height使用CSS会更好。仅当 textarea 设置为不换行时,您的代码才有效。

尝试这样的事情:

$('textarea').keyup(function() {
    this.style.height = (this.scrollHeight+8)+"px";
});

然后,如果您transition在 textarea 上设置了合适的属性,它将动画化。

于 2013-03-17T12:37:58.827 回答
0

你也可以试试:http: //jsfiddle.net/bhzte/1/

$('textarea').keyup(function() {
    var that = $(this);
    var rows = that.val().split("\n").length;
    that.attr('rows', rows);
    var lh = parseInt(that.css('line-height');)
        that.animate({height:lh*rows})
});

您可以在 css 文件中设置行高,样式 attr<textarea style="18px"></textarea> 或使用 jquery:

$('textarea').css({'line-height':'18px'}).keyup(...});


更新

你可以做这样的事情来避免缩小:http: //jsfiddle.net/bhzte/4/

于 2013-03-17T12:43:27.840 回答
0

尝试这个

$('textarea').keyup(function(e) {
  var code = (e.keyCode ? e.keyCode : e.which);
  if (code==13) {
    $(this).attr('rows', $(this).val().split("\n").length + 1);
  }
});

http://jsfiddle.net/A8nxA/

于 2013-03-17T12:44:44.617 回答