还有另一个关于这个的帖子,我试过了。但有一个问题:如果你删除内容,文本区域不会缩小。我找不到任何方法将其缩小到正确的大小- clientHeight值返回为文本区域的完整大小,而不是它的内容。

该页面的代码如下:

function FitToContent(id, maxHeight)
{
   var text = id && id.style ? id : document.getElementById(id);
   if ( !text )
      return;

   var adjustedHeight = text.clientHeight;
   if ( !maxHeight || maxHeight > adjustedHeight )
   {
      adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
      if ( maxHeight )
         adjustedHeight = Math.min(maxHeight, adjustedHeight);
      if ( adjustedHeight > text.clientHeight )
         text.style.height = adjustedHeight + "px";
   }
}

window.onload = function() {
    document.getElementById("ta").onkeyup = function() {
      FitToContent( this, 500 )
    };
}

当前回答

我能够设置TextArea大小在IE9和Chrome与下面的jQuery函数。它绑定到$(document).ready()函数中定义的选择器中的textarea对象。

function autoResize(obj, size) {
    obj.keyup(function () {
        if ($(this).val().length > size-1) {
            $(this).val( function() {
                $(this).height(function() {
                    return this.scrollHeight + 13;
                });
                alert('The maximum comment length is '+size+' characters.');
                return $(this).val().substring(0, size-1);
            });
        }
        $(this).height(function() {
            if  ($(this).val() == '') {
                return 15;
            } else {
                $(this).height(15);
                return ($(this).attr('scrollHeight')-2);
            }
        });
    }).keyup();
}

在我的$(document).ready()函数中,我对本页上的所有textarea调用有以下调用。

$('textarea').each( function() {
        autoResize($(this), 250);
});

其中250是文本区域的字符限制。这将增加到文本大小所允许的大小(基于您的字符数和字体大小)。当您从文本区域中删除字符或用户最初粘贴了太多文本时,它还会适当地缩小文本区域。

其他回答

对于那些正在寻找特定角度的答案的人,你可以使用这个选项来设置默认行数。

create directive

    @Directive({
  selector: '[appTextAreaAutoHeight]'
})
export class TextAreaAutoHeightDirective implements AfterViewInit {
  private row = 1;
  constructor(private el: ElementRef) {
    this.row = el.nativeElement.rows;
  }
  ngAfterViewInit(): void {
    const elem = this.el.nativeElement;
    elem.style.height = "1px";
    elem.style.minHeight = (this.row * elem.scrollHeight) + "px";
  }

  @HostListener('input', ['$event.target'])
  onInput(elem: any) {
    elem.style.height = "1px";
    elem.style.height = (elem.scrollHeight) + "px";
  }
}

使用方法:

<textarea id="title" rows="3" class="col-12 p-1 fs-15 fw-reg 
  rounded-1" appTextAreaAutoHeight
  placeholder="...*******$$$"></textarea>

MakeTextAreaResisable使用qQuery

function MakeTextAreaResisable(id) {
    var o = $(id);
    o.css("overflow-y", "hidden");

    function ResizeTextArea() {
        o.height('auto');
        o.height(o[0].scrollHeight);
    }

    o.on('change', function (e) {
        ResizeTextArea();
    });

    o.on('cut paste drop keydown', function (e) {
        window.setTimeout(ResizeTextArea, 0);
    });

    o.focus();
    o.select();
    ResizeTextArea();
}

我在常见的浏览器中测试了脚本,在Chrome和Safari中失败了。这是因为不断更新的scrollHeight变量。

我已经使用jQuery应用了wrettledgoat脚本,并添加了chrome修复

function fitToContent(/* JQuery */text, /* Number */maxHeight) {
    var adjustedHeight = text.height();
    var relative_error = parseInt(text.attr('relative_error'));
    if (!maxHeight || maxHeight > adjustedHeight) {
        adjustedHeight = Math.max(text[0].scrollHeight, adjustedHeight);
        if (maxHeight)
            adjustedHeight = Math.min(maxHeight, adjustedHeight);
        if ((adjustedHeight - relative_error) > text.height()) {
            text.css('height', (adjustedHeight - relative_error) + "px");
            // chrome fix
            if (text[0].scrollHeight != adjustedHeight) {
                var relative = text[0].scrollHeight - adjustedHeight;
                if (relative_error != relative) {
                    text.attr('relative_error', relative + relative_error);
                }
            }
        }
    }
}

function autoResizeText(/* Number */maxHeight) {
    var resize = function() {
        fitToContent($(this), maxHeight);
    };
    $("textarea").attr('relative_error', 0);
    $("textarea").each(resize);
    $("textarea").keyup(resize).keydown(resize);
}

我知道我迟到了,但我遇到的最简单的解决方案是分割你的文本区域内容在新的行字符和更新文本区域元素的行。

<textarea id="my-text-area"></textarea>

<script>
  $(function() {
    const txtArea = $('#my-text-area')
    const val = txtArea.val()
    const rowLength = val.split('\n')
    txtArea.attr('rows', rowLength)
  })
</script>

我的实现非常简单,计算输入中的行数(并且最少2行,以显示它是一个textarea):

textarea.rows = Math.max(2, textarea.value.split("\n").length) // # oninput

刺激的完整工作示例:https://jsbin.com/kajosolini/1/edit?html,js,output

(这适用于浏览器的手动调整大小句柄,例如)