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

当前回答

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

其他回答

一个完整而简单的解决方案

更新2022-08-30 (默认增加了单行多文本框的支持)

下面的代码将工作:

按键输入。 粘贴文本(右键单击并ctrl+v)。 剪切文本(右键单击并ctrl+x)。 与预加载文本。 与所有的文本区域(多行文本框的)网站宽。 使用Firefox (v31-109测试)。 Chrome (v37-108测试)。 使用IE (v9-v11测试)。 使用Edge (v14-v108测试)。 IOS Safari。 Android浏览器。 JavaScript严格模式。


选项1(使用jQuery)

此选项需要jQuery,并且已经过测试,适用于1.7.2 - 3.6.3

简单(将jQuery代码添加到主脚本文件中,然后忘记它)。

$("textarea").each(function () { this.setAttribute("style", "height:" + (this.scrollHeight) + "px;overflow-y:hidden;"); }).on("input", function () { this.style.height = 0; this.style.height = (this.scrollHeight) + "px"; }); <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.6.3.min.js"></script> <textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT. This JavaScript should now add better support for IOS browsers and Android browsers.</textarea> <textarea placeholder="Type, paste, cut text here..."></textarea>

在jsfiddle上测试


OPTION 2(纯JavaScript)

简单(将此JavaScript添加到主脚本文件中,然后忘记它)。

const tx = document.getElementsByTagName("textarea"); for (let i = 0; i < tx.length; i++) { tx[i].setAttribute("style", "height:" + (tx[i].scrollHeight) + "px;overflow-y:hidden;"); tx[i].addEventListener("input", OnInput, false); } function OnInput() { this.style.height = 0; this.style.height = (this.scrollHeight) + "px"; } <textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT. This JavaScript should now add better support for IOS browsers and Android browsers.</textarea> <textarea placeholder="Type, paste, cut text here..."></textarea>

在jsfiddle上测试


选项3 (jQuery扩展)

如果你想应用进一步的链接到文本区域,你想自动调整大小。

jQuery.fn.extend({
  autoHeight: function () {
    function autoHeight_(element) {
      return jQuery(element)
        .css({ "height": 0, "overflow-y": "hidden" })
        .height(element.scrollHeight);
    }
    return this.each(function() {
      autoHeight_(this).on("input", function() {
        autoHeight_(this);
      });
    });
  }
});

使用$("textarea")调用。autoheight ()


通过javascript更新文本区域

当通过JavaScript向文本区域注入内容时,添加以下代码来调用选项1中的函数。

$("textarea").trigger("input");

预设文本区域高度

要修复文本区域的初始高度,你需要添加另一个条件:

const txHeight = 16; const tx = document.getElementsByTagName("textarea"); for (let i = 0; i < tx.length; i++) { if (tx[i].value == '') { tx[i].setAttribute("style", "height:" + txHeight + "px;overflow-y:hidden;"); } else { tx[i].setAttribute("style", "height:" + (tx[i].scrollHeight) + "px;overflow-y:hidden;"); } tx[i].addEventListener("input", OnInput, false); } function OnInput(e) { this.style.height = 0; this.style.height = (this.scrollHeight) + "px"; } <textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT. This JavaScript should now add better support for IOS browsers and Android browsers.</textarea> <textarea placeholder="Type, paste, cut text here..."></textarea>

作为一种不同的方法,您可以使用<span>来自动调整它的大小。你需要通过添加contentteditable ="true"属性使其可编辑,这样就完成了:

div { 宽度:200 px; } 跨度{ 边框:1px实心#000; 填充:5 px; } < div > <span contenteditable="true">此文本可以由用户编辑</span> < / div >

这种方法的唯一问题是,如果希望将值作为表单的一部分提交,就必须自己用JavaScript完成。这样做相对容易。例如,您可以添加一个隐藏字段,并在表单的onsubmit事件中将span的值赋给隐藏字段,然后该隐藏字段将自动与表单一起提交。

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

自动调整大小

https://github.com/jackmoore/autosize

只是作品,独立,很受欢迎(截至2018年10月,3.0k+ GitHub星),可在cdnjs上使用)和轻量级(~3.5k)。演示:

<textarea id=“autosize” style=“width:200px;”>a 我一 C</textarea> <script src=“https://cdnjs.cloudflare.com/ajax/libs/autosize.js/4.0.2/autosize.min.js”></script> <script>autosize(document.querySelectorAll('#autosize'));</script>

顺便说一句,如果你正在使用ACE编辑器,请使用maxLines: Infinity:自动调整ACE Cloud 9编辑器中的内容高度

如果你不需要支持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>

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