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

当前回答

还有一种略有不同的方法。

<div style="position: relative">
  <pre style="white-space: pre-wrap; word-wrap: break-word"></pre>
  <textarea style="position: absolute; top: 0; left: 0; width: 100%; height: 100%"></textarea>
</div>

这个想法是将文本从textarea复制到pre,让CSS确保它们具有相同的大小。

这样做的好处是框架提供了简单的工具来移动文本而不涉及任何事件。也就是说,在AngularJS中,你可以在textarea中添加ng-model="foo" ng-trim="false",在pre中添加ng-bind="foo + '\n'"。看小提琴。

只需确保pre的字体大小与textarea相同。

其他回答

$('textarea').bind('keyup change', function() {
    var $this = $(this), $offset = this.offsetHeight;
    $offset > $this.height() && $offset < 300 ?
        $this.css('height ', $offset)
            .attr('rows', $this.val().split('\n').length)
            .css({'height' : $this.attr('scrollHeight'),'overflow' : 'hidden'}) :
        $this.css('overflow','auto');
});

你可以使用JQuery在输入时扩展文本区域:

$(文档);(“文本区域”)。每个(函数(){ Var offset = this。offsetHeight - this.clientHeight; (美元)。On ('keyup input focus', function () { $(this).css('height', 'auto').css('height', this。scrollHeight + offset); }); }); < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> < div > < textarea name = "注意" > < / >文本区域 < div >

对于那些正在寻找特定角度的答案的人,你可以使用这个选项来设置默认行数。

create directive

    @Directive({
  selector: '[appTextAreaAutoHeight]'
})
export class TextAreaAutoHeightDirective implements AfterViewInit {
  private row = 1;
  constructor(private el: ElementRef) {
    this.row = el.nativeElement.rows;
  }
  ngAfterViewInit(): void {
    const elem = this.el.nativeElement;
    elem.style.height = "1px";
    elem.style.minHeight = (this.row * elem.scrollHeight) + "px";
  }

  @HostListener('input', ['$event.target'])
  onInput(elem: any) {
    elem.style.height = "1px";
    elem.style.height = (elem.scrollHeight) + "px";
  }
}

使用方法:

<textarea id="title" rows="3" class="col-12 p-1 fs-15 fw-reg 
  rounded-1" appTextAreaAutoHeight
  placeholder="...*******$$$"></textarea>

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

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

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

请看看jsFiddle。

我创建了一个小的(7kb)自定义元素,为您处理所有这些调整大小的逻辑。

它可以在任何地方工作,因为它是作为自定义元素实现的。包括:虚拟dom (React, Elm等),服务器端呈现的东西,如PHP和简单乏味的HTML文件。

除了监听输入事件外,它还有一个计时器,每100毫秒触发一次,以确保在文本内容通过其他方式发生变化的情况下,事情仍在工作。

下面是它的工作原理:

// At the top of one of your Javascript files
import "autoheight-textarea";

或作为脚本标记包含

<script src="//cdn.jsdelivr.net/npm/autoheight-textarea@1.0.1/dist/main.min.js"></script>

然后像这样包装你的textarea元素

HTML文件

<autoheight-textarea>
  <textarea rows="4" placeholder="Type something"></textarea>
<autoheight-textarea>

React.js组件

const MyComponent = () => {
  return (
    <autoheight-textarea>
      <textarea rows={4} placeholder="Type something..." />
    </autoheight-textarea>
  );
}

下面是Codesandbox上的一个基本演示:https://codesandbox.io/s/unruffled-http-2vm4c

你可以在这里获取软件包:https://www.npmjs.com/package/autoheight-textarea

如果你只是想看看调整大小的逻辑,你可以看看这个函数:https://github.com/Ahrengot/autoheight-textarea/blob/master/src/index.ts#L74-L85