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

其他回答

对我来说,最好的解决方案(既有效又简短)是:

    $(document).on('input', 'textarea', function () {
        $(this).outerHeight(38).outerHeight(this.scrollHeight); // 38 or '1em' -min-height
    }); 

它的工作就像一个魅力没有任何闪烁的粘贴(与鼠标也),切割,进入,它缩小到正确的大小。

请看看jsFiddle。

下面的工作用于剪切,粘贴等,不管这些操作是来自鼠标,键盘快捷键,从菜单栏选择一个选项…有几个答案采用了类似的方法,但它们没有考虑到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,所以我真的希望这是足够好的支持。

我发现最好的方法是:

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

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

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

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Textarea autoresize</title>
    <style>
    textarea {
        overflow: hidden;
    }
    </style>
    <script>
    function resizeTextarea(ev) {
        this.style.height = '24px';
        this.style.height = this.scrollHeight + 12 + 'px';
    }

    var te = document.querySelector('textarea');
    te.addEventListener('input', resizeTextarea);
    </script>
</head>
<body>
    <textarea></textarea>
</body>
</html>

在Firefox 14和Chromium 18中测试。数字24和12是任意的,测试一下看看哪个最适合你。

你可以不使用样式和脚本标记,但这会变得有点混乱(这是老式的HTML+JS,不鼓励使用)。

<textarea style="overflow: hidden" onkeyup="this.style.height='24px'; this.style.height = this.scrollHeight + 12 + 'px';"></textarea>

编辑:现代化的代码。将onkeyup属性更改为addEventListener。 编辑:keydown工作比keyup更好 编辑:在使用之前声明函数 编辑:输入工作更好的按键(thnx @WASD42 & @MA-Maddin)

斯菲德尔

以下是我在使用MVC HTML Helper for TextArea时所做的。我有相当多的textarea元素,所以必须使用模型Id来区分它们。

 @Html.TextAreaFor(m => m.Text, 2, 1, new { id = "text" + Model.Id, onkeyup = "resizeTextBox(" + Model.Id + ");" })

并在脚本中添加了这个:

   function resizeTextBox(ID) {            
        var text = document.getElementById('text' + ID);
        text.style.height = 'auto';
        text.style.height = text.scrollHeight + 'px';            
    }

我在IE10和Firefox23上进行了测试