还有另一个关于这个的帖子,我试过了。但有一个问题:如果你删除内容,文本区域不会缩小。我找不到任何方法将其缩小到正确的大小- 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.auto-grow").each( function(){
    $(this).keyup(function(){
        $(this).height( $(this)[0].scrollHeight - Number( $(this).css("font-size").replace("px", "") ) );
    });
});

其他方法有一个字体大小的错误。

这就是为什么这是最好的。

其他回答

如果你不需要支持IE8,你可以使用input事件:

var resizingTextareas = [].slice.call(document.querySelectorAll('textarea[autoresize]'));

resizingTextareas.forEach(function(textarea) {
  textarea.addEventListener('input', autoresize, false);
});

function autoresize() {
  this.style.height = 'auto';
  this.style.height = this.scrollHeight+'px';
  this.scrollTop = this.scrollHeight;
  window.scrollTo(window.scrollLeft,(this.scrollTop+this.scrollHeight));
}

现在你只需要添加一些CSS,你就完成了:

textarea[autoresize] {
  display: block;
  overflow: hidden;
  resize: none;
}

用法:

<textarea autoresize>Type here and I’ll resize.</textarea>

你可以在我的博客文章中阅读更多关于它是如何工作的。

我知道用jquery实现这个的一个简短而正确的方法。没有额外的隐藏div需要和工作在大多数浏览器

<script type="text/javascript">$(function(){
$("textarea").live("keyup keydown",function(){
var h=$(this);
h.height(60).height(h[0].scrollHeight);//where 60 is minimum height of textarea
});});

</script>

我发现最好的方法是:

$("textarea.auto-grow").each( function(){
    $(this).keyup(function(){
        $(this).height( $(this)[0].scrollHeight - Number( $(this).css("font-size").replace("px", "") ) );
    });
});

其他方法有一个字体大小的错误。

这就是为什么这是最好的。

这里有一个明确的答案:

退格增加滚动高度的值

它使用现代ES6语法,解决了添加或删除内容时精确调整大小的问题。它解决了滚动高度值不断变化的问题。

jQuery的解决方案是设置文本区域的高度为'auto',检查scrollHeight,然后调整文本区域的高度,每次文本区域改变(JSFiddle):

$('textarea').on( 'input', function(){
    $(this).height( 'auto' ).height( this.scrollHeight );
});

如果你在动态添加文本区域(通过AJAX或其他方式),你可以在$(document)中添加这个。准备好确保所有带有类'autoheight'的文本区域保持与它们的内容相同的高度:

$(document).on( 'input', 'textarea.autoheight', function() {
    $(this).height( 'auto' ).height( this.scrollHeight );
});

测试和工作在Chrome, Firefox, Opera和IE。还支持剪切和粘贴,长字等。