还有另一个关于这个的帖子,我试过了。但有一个问题:如果你删除内容,文本区域不会缩小。我找不到任何方法将其缩小到正确的大小- 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 )
    };
}

当前回答

那些想要在Angular的新版本中实现同样功能的人。

抓取文本区域元素引用。

@ViewChild('textArea', { read: ElementRef }) textArea: ElementRef;

public autoShrinkGrow() {
    textArea.style.overflow = 'hidden';
    textArea.style.height = '0px';
    textArea.style.height = textArea.scrollHeight + 'px';
}

<textarea (keyup)="autoGrow()" #textArea></textarea>

我还添加了另一个用例,可能方便一些用户阅读线程,当用户想增加文本区域的高度到一定高度,然后有溢出:滚动它,上面的方法可以扩展到实现上述用例。

  public autoGrowShrinkToCertainHeight() {
    const textArea = this.textArea.nativeElement;
    if (textArea.scrollHeight > 77) {
      textArea.style.overflow = 'auto';
      return;
    }
    else {
      textArea.style.overflow = 'hidden';
      textArea.style.height = '0px';
      textArea.style.height = textArea.scrollHeight + 'px';
    }
  }

其他回答

我推荐来自http://javierjulio.github.io/textarea-autosize的javascript库。

每个注释,添加插件使用的示例代码块:

<textarea class="js-auto-size" rows="1"></textarea>

<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="jquery.textarea_autosize.min.js"></script>
<script>
$('textarea.js-auto-size').textareaAutoSize();
</script>

最低要求CSS:

textarea {
  box-sizing: border-box;
  max-height: 160px; // optional but recommended
  min-height: 38px;
  overflow-x: hidden; // for Firefox (issue #5)
}
$('textarea').bind('keyup change', function() {
    var $this = $(this), $offset = this.offsetHeight;
    $offset > $this.height() && $offset < 300 ?
        $this.css('height ', $offset)
            .attr('rows', $this.val().split('\n').length)
            .css({'height' : $this.attr('scrollHeight'),'overflow' : 'hidden'}) :
        $this.css('overflow','auto');
});

下面的工作用于剪切,粘贴等,不管这些操作是来自鼠标,键盘快捷键,从菜单栏选择一个选项…有几个答案采用了类似的方法,但它们没有考虑到box-sizing,这就是为什么它们错误地应用了样式overflow: hidden。

我执行以下操作,这也适用于max-height和rows的最小高度和最大高度。

function adjust() { var style = this.currentStyle || window.getComputedStyle(this); var boxSizing = style.boxSizing === 'border-box' ? parseInt(style.borderBottomWidth, 10) + parseInt(style.borderTopWidth, 10) : 0; this.style.height = ''; this.style.height = (this.scrollHeight + boxSizing) + 'px'; }; var textarea = document.getElementById("ta"); if ('onpropertychange' in textarea) { // IE textarea.onpropertychange = adjust; } else if ('oninput' in textarea) { textarea.oninput = adjust; } setTimeout(adjust.bind(textarea)); textarea { resize: none; max-height: 150px; border: 1px solid #999; outline: none; font: 18px sans-serif; color: #333; width: 100%; padding: 8px 14px; box-sizing: border-box; } <textarea rows="3" id="ta"> Try adding several lines to this. </textarea>

为了绝对完整,你应该在以下几种情况下调用adjust函数:

窗口调整大小事件(如果文本区域的宽度随着窗口调整大小而改变),或者其他改变文本区域宽度的事件 当文本区域的显示样式属性发生变化时,例如当它从none(隐藏)变为block时 当文本区域的值以编程方式更改时

注意使用window。getComputedStyle或getcurrentstyle在计算上可能有点昂贵,所以您可能想要缓存结果。

适用于IE6,所以我真的希望这是足够好的支持。

一个更简单、更清晰的方法是:

// adjust height of textarea.auto-height
$(document).on( 'keyup', 'textarea.auto-height', function (e){
    $(this).css('height', 'auto' ); // you can have this here or declared in CSS instead
    $(this).height( this.scrollHeight );
}).keyup();

//和CSS

textarea.auto-height {
    resize: vertical;
    max-height: 600px; /* set as you need it */
    height: auto;      /* can be set here of in JS */
    overflow-y: auto;
    word-wrap:break-word
}

所有需要做的就是将.auto-height类添加到您想要的目标文本区域。

在FF, Chrome和Safari测试。如果这对你不起作用,请告诉我,不管是什么原因。但是,这是我发现的最简单明了的方法。而且效果非常好!: D

这是一个jQuery版本的Moussawi7的答案。

$(函数(){ $ (" textarea.auto-grow”)。On ("input", function() { Var元素= $(this)[0]; Element.style.height = "5px"; element.style.height = (element.scrollHeight) + "px"; }); }) textarea { 调整:没有; 溢出:汽车; 宽度:100%; 最小高度:50 px; max-height: 150 px; } < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> < textarea类= " auto-grow " > < / >文本区域