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

当前回答

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

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

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

请看看jsFiddle。

其他回答

这段代码也适用于粘贴和选择删除。

onKeyPressTextMessage = function(){ var textArea =event.currentTarget; 文本区域.样式.高度 = '自动'; 文本区域.样式.高度 = 文本区域.滚动高度 + 'px'; }; <textation onkeyup=“onKeyPressTextMessage(event)” name=“welcomeContentTmpl” id=“welcomeContent” onblur=“onblurWelcomeTitle(event)” rows=“2” cols=“40” maxlength=“320”></textarea>

这是JSFiddle

对于Angular 2+,就这么做

<textarea (keydown)="resize($event)"></textarea>


resize(e) {
    setTimeout(() => {
      e.target.style.height = 'auto';
      e.target.style.height = (e.target.scrollHeight)+'px';
    }, 0);
  }

textarea {
  resize: none;
  overflow: hidden;
}

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

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

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

改进的响应式纯JS解决方案,以@DreamTeK的第二个选项为基础

下面还处理了底部填充以及窗口大小的调整。像这样,这对我来说是一个近乎完美的解决方案。非常感谢他。

let textareas = document.getElementsByClassName("auto-resize-textarea"); // Loop through textareas and add event listeners as well as other needed css attributes for (const textarea of textareas) { // Initially set height as otherwise the textarea is not high enough on load textarea.style.height = textarea.scrollHeight.toString(); // Hide scrollbar textarea.style.overflowY = 'hidden'; // Call resize function with "this" context once during initialisation as it's too high otherwise resizeTextarea.call(textarea); // Add event listener to resize textarea on input textarea.addEventListener('input', resizeTextarea, false); // Also resize textarea on window resize event binding textarea to be "this" window.addEventListener('resize', resizeTextarea.bind(textarea), false); } function resizeTextarea() { // Textareas have default 2px padding and if not set it returns 0px let padding = window.getComputedStyle(this).getPropertyValue('padding-bottom'); // getPropertyValue('padding-bottom') returns "px" at the end it needs to be removed to be added to scrollHeight padding = parseInt(padding.replace('px','')); this.style.height = "auto"; this.style.height = (this.scrollHeight) + "px"; } textarea { width:40%; padding:20px 25px; border-radius: 20px; } <textarea class="auto-resize-textarea">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</textarea> <textarea placeholder="Type, paste, cut text here..." class="auto-resize-textarea"></textarea>

注意:jsfiddle有一个奇怪的问题,文本区域太高,底部有太多的空间,但是复制和粘贴这段代码到一个空的html文件是完美的。

有一个小问题,但当滚动条出现在页面和文本区域收缩和包装文本,并创建一个新的行。上面的函数没有考虑到这一点,我提出了一个问题,但似乎没有人知道解决办法。如果你有解决这个问题的建议,我将非常高兴。

这里的一些答案没有考虑到填充。

假设你有一个maxHeight你不想去,这对我有用:

    // obviously requires jQuery

    // element is the textarea DOM node

    var $el = $(element);
    // inner height is height + padding
    // outerHeight includes border (and possibly margins too?)
    var padding = $el.innerHeight() - $el.height();
    var originalHeight = $el.height();

    // XXX: Don't leave this hardcoded
    var maxHeight = 300;

    var adjust = function() {
        // reset it to the original height so that scrollHeight makes sense
        $el.height(originalHeight);

        // this is the desired height (adjusted to content size)
        var height = element.scrollHeight - padding;

        // If you don't want a maxHeight, you can ignore this
        height = Math.min(height, maxHeight);

        // Set the height to the new adjusted height
        $el.height(height);
    }

    // The input event only works on modern browsers
    element.addEventListener('input', adjust);