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

当前回答

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

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

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

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

其他回答

React的一个示例实现:

const { useLayoutEffect, useState, useRef } = React; const TextArea = () => { const ref = useRef(); const [value, setValue] = useState('Some initial text that both wraps and uses\nnew\nlines'); // This only tracks the auto-sized height so we can tell if the user has manually resized const autoHeight = useRef(); useLayoutEffect(() => { if (!ref.current) { return; } if ( autoHeight.current !== undefined && ref.current.style.height !== autoHeight.current ) { // don't auto size if the user has manually changed the height return; } ref.current.style.height = "auto"; ref.current.style.overflow = "hidden"; const next = `${ref.current.scrollHeight}px`; ref.current.style.height = next; autoHeight.current = next; ref.current.style.overflow = "auto"; }, [value, ref, autoHeight]); return ( <textarea ref={ref} style={{ resize: 'vertical', minHeight: '1em', }} value={value} onChange={event => setValue(event.target.value)} /> ); } ReactDOM.render(<TextArea />, document.getElementById('app')) <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script> <div id="app"></div>

这是一种基于行的方法,允许您为文本区域设置最大行数,之后文本区域将显示滚动条。除了以rows属性的形式调整它的高度之外,它还会在键入或执行剪切和粘贴之类的操作时自动扩展它的宽度。

如果文本区域没有任何内容,只有一个占位符,它将根据占位符文本调整其宽度和高度。

这个版本的一个缺点是,它将继续无限增加它的宽度基于文本宽度。因此,你需要为文本区域设置一个max-width值。简单的max-width: 100%;也会有效果。这个宽度扩展特性主要基于type="text"的输入字段。你可以在这个答案中了解更多。

const textarea = document.querySelector('textarea'); setTextareaWidthHeight(textarea); textarea.addEventListener('input', setTextareaWidthHeight.bind(this, textarea)); function getInputWidth(element) { const text = element.value || element.placeholder; const elementStyle = window.getComputedStyle(element); const fontProperty = elementStyle.font; const horizontalBorder = parseFloat(elementStyle.borderLeftWidth) + parseFloat(elementStyle.borderRightWidth); const horizontalPadding = parseFloat(elementStyle.paddingLeft) + parseFloat(elementStyle.paddingRight); const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); context.font = fontProperty; const textWidth = context.measureText(text).width; const totalWidth = horizontalBorder + horizontalPadding + textWidth + "px"; return totalWidth; } function setTextareaWidthHeight(element) { // store minimum and maximum rows attribute value that should be imposed const minRows = 1; const maxRows = 5; // store initial inline overflow property value in a variable for later reverting to original condition const initialInlineOverflowY = element.style.overflowY; // change overflow-y property value to hidden to overcome inconsistent width differences caused by any scrollbar width element.style.overflowY = 'hidden'; const totalWidth = getInputWidth(element); element.style.width = totalWidth; let rows = minRows; element.setAttribute("rows", rows); while (rows <= maxRows && element.scrollHeight !== element.clientHeight) { element.setAttribute("rows", rows); rows++; } // change overflow to its original condition if (initialInlineOverflowY) { element.style.overflowY = initialInlineOverflowY; } else { element.style.removeProperty("overflow-y"); } } textarea { max-width: 100%; } <textarea placeholder="Lorem ipsum dolor sit amet"></textarea>

这适用于我(Firefox 3.6/4.0和Chrome 10/11):

var observe; if (window.attachEvent) { observe = function (element, event, handler) { element.attachEvent('on'+event, handler); }; } else { observe = function (element, event, handler) { element.addEventListener(event, handler, false); }; } function init () { var text = document.getElementById('text'); function resize () { text.style.height = 'auto'; text.style.height = text.scrollHeight+'px'; } /* 0-timeout to get the already changed text */ function delayedResize () { window.setTimeout(resize, 0); } observe(text, 'change', resize); observe(text, 'cut', delayedResize); observe(text, 'paste', delayedResize); observe(text, 'drop', delayedResize); observe(text, 'keydown', delayedResize); text.focus(); text.select(); resize(); } textarea { border: 0 none white; overflow: hidden; padding: 0; outline: none; background-color: #D0D0D0; } <body onload="init();"> <textarea rows="1" style="height:1em;" id="text"></textarea> </body>

如果你想试试jsfiddle 它从一行开始,只增加所需的确切数量。对于一个单一的文本区域是可以的,但是我想写一些东西,我将有很多很多这样的文本区域(大约像一个大文本文档中通常有行一样多)。在这种情况下,它真的很慢。(在Firefox中,它慢得离谱。)所以我真的很喜欢使用纯CSS的方法。这将是可能的contentteditable,但我希望它是纯文本。

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

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

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

请看看jsFiddle。

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

更新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>