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

其他回答

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>

你可以使用这段代码来计算一个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;
  }

}

我创建了一个小的(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

您正在使用当前clientHeight和内容scrollHeight的较高值。当您通过删除内容使scrollHeight变小时,计算区域不能变小,因为先前根据样式设置的clientHeight。高度,是撑开它。您可以使用scrollHeight的max()和预定义的或从textarea.rows中计算的最小高度值。

In general you probably shouldn't really rely on scrollHeight on form controls. Apart from scrollHeight being traditionally less widely-supported than some of the other IE extensions, HTML/CSS says nothing about how form controls are implemented internally and you aren't guaranteed scrollHeight will be anything meaningful. (Traditionally some browsers have used OS widgets for the task, making CSS and DOM interaction on their internals impossible.) At least sniff for scrollHeight/clientHeight's existance before trying to enable the effect.

另一种可能的替代方法来避免这个问题,如果重要的是,它可以更广泛地工作,可能是使用一个隐藏的div大小相同的文本区域的宽度,并设置在相同的字体。在keyup上,您将文本从文本区域复制到隐藏div中的文本节点(记住用换行符替换'\n',如果使用innerHTML则正确转义'<'/'&')。然后简单地测量div的offsetHeight将给你你需要的高度。

一个使用React的简单方法。

...
const textareaRef = useRef();

const handleChange = (e) => {
  textareaRef.current.style.height = "auto";
  textareaRef.current.style.height = textareaRef.current.scrollHeight + "px";
};

return <textarea ref={textareaRef} onChange={handleChange} />;