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

当前回答

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

假设你有一个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);

其他回答

这是一个jQuery版本的Moussawi7的答案。

$(函数(){ $ (" textarea.auto-grow”)。On ("input", function() { Var元素= $(this)[0]; Element.style.height = "5px"; element.style.height = (element.scrollHeight) + "px"; }); }) textarea { 调整:没有; 溢出:汽车; 宽度:100%; 最小高度:50 px; max-height: 150 px; } < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> < textarea类= " auto-grow " > < / >文本区域

你可以使用下面的代码:

Coffescript:

jQuery.fn.extend autoHeightTextarea: ->
  autoHeightTextarea_ = (element) ->
    jQuery(element).css(
      'height': 'auto'
      'overflow-y': 'hidden').height element.scrollHeight

  @each ->
    autoHeightTextarea_(@).on 'input', ->
      autoHeightTextarea_ @

$('textarea_class_or_id`').autoHeightTextarea()

Javascript

jQuery.fn.extend({
  autoHeightTextarea: function() {
    var autoHeightTextarea_;
    autoHeightTextarea_ = function(element) {
      return jQuery(element).css({
        'height': 'auto',
        'overflow-y': 'hidden'
      }).height(element.scrollHeight);
    };
    return this.each(function() {
      return autoHeightTextarea_(this).on('input', function() {
        return autoHeightTextarea_(this);
      });
    });
  }
});

$('textarea_class_or_id`').autoHeightTextarea();

这是一种基于行的方法,允许您为文本区域设置最大行数,之后文本区域将显示滚动条。除了以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>

jQuery的解决方案 请根据实际情况调整CSS

css……

div#container textarea {
    min-width: 270px;
    width: 270px;
    height: 22px;
    line-height: 24px;
    min-height: 22px;
    overflow-y: hidden; /* fixes scrollbar flash - kudos to @brettjonesdev */
    padding-top: 1.1em; /* fixes text jump on Enter keypress */
}

javascript……

// auto adjust the height of
$('#container').delegate( 'textarea', 'keydown', function (){
    $(this).height( 0 );
    $(this).height( this.scrollHeight );
});
$('#container').find( 'textarea' ).keydown();

或替代jQuery 1.7+…

// auto adjust the height of
$('#container').on( 'keyup', 'textarea', function (){
    $(this).height( 0 );
    $(this).height( this.scrollHeight );
});
$('#container').find( 'textarea' ).keyup();

我已经创建了一个具有绝对最小样式的小提琴作为您的实验的起点…… http://jsfiddle.net/53eAy/951/

你可以使用这段代码来计算一个textarea需要的行数:

textarea.rows = 1;
    if (textarea.scrollHeight > textarea.clientHeight)
      textarea.rows = textarea.scrollHeight / textarea.clientHeight;

在输入和窗口:resize事件上计算它以获得自动调整大小的效果。Angular中的例子:

模板代码:

<textarea rows="1" reAutoWrap></textarea>

auto-wrap.directive.ts

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: 'textarea[reAutoWrap]',
})
export class AutoWrapDirective {

  private readonly textarea: HTMLTextAreaElement;

  constructor(el: ElementRef) {
    this.textarea = el.nativeElement;
  }

  @HostListener('input') onInput() {
    this.resize();
  }

  @HostListener('window:resize') onChange() {
    this.resize();
  }

  private resize() {
    this.textarea.rows = 1;
    if (this.textarea.scrollHeight > this.textarea.clientHeight)
      this.textarea.rows = this.textarea.scrollHeight / this.textarea.clientHeight;
  }

}