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

当前回答

我对多个文本区域使用了以下代码。在Chrome 12, Firefox 5和IE 9中工作良好,即使在文本区域执行删除,剪切和粘贴操作。

function attachAutoResizeEvents() { for (i = 1; i <= 4; i++) { var txtX = document.getElementById('txt' + i) var minH = txtX.style.height.substr(0, txtX.style.height.indexOf('px')) txtX.onchange = new Function("resize(this," + minH + ")") txtX.onkeyup = new Function("resize(this," + minH + ")") txtX.onchange(txtX, minH) } } function resize(txtX, minH) { txtX.style.height = 'auto' // required when delete, cut or paste is performed txtX.style.height = txtX.scrollHeight + 'px' if (txtX.scrollHeight <= minH) txtX.style.height = minH + 'px' } window.onload = attachAutoResizeEvents textarea { border: 0 none; overflow: hidden; outline: none; background-color: #eee } <textarea style='height:100px;font-family:arial' id="txt1"></textarea> <textarea style='height:125px;font-family:arial' id="txt2"></textarea> <textarea style='height:150px;font-family:arial' id="txt3"></textarea> <textarea style='height:175px;font-family:arial' id="txt4"></textarea>

其他回答

这里有一个明确的答案:

退格增加滚动高度的值

它使用现代ES6语法,解决了添加或删除内容时精确调整大小的问题。它解决了滚动高度值不断变化的问题。

我在常见的浏览器中测试了脚本,在Chrome和Safari中失败了。这是因为不断更新的scrollHeight变量。

我已经使用jQuery应用了wrettledgoat脚本,并添加了chrome修复

function fitToContent(/* JQuery */text, /* Number */maxHeight) {
    var adjustedHeight = text.height();
    var relative_error = parseInt(text.attr('relative_error'));
    if (!maxHeight || maxHeight > adjustedHeight) {
        adjustedHeight = Math.max(text[0].scrollHeight, adjustedHeight);
        if (maxHeight)
            adjustedHeight = Math.min(maxHeight, adjustedHeight);
        if ((adjustedHeight - relative_error) > text.height()) {
            text.css('height', (adjustedHeight - relative_error) + "px");
            // chrome fix
            if (text[0].scrollHeight != adjustedHeight) {
                var relative = text[0].scrollHeight - adjustedHeight;
                if (relative_error != relative) {
                    text.attr('relative_error', relative + relative_error);
                }
            }
        }
    }
}

function autoResizeText(/* Number */maxHeight) {
    var resize = function() {
        fitToContent($(this), maxHeight);
    };
    $("textarea").attr('relative_error', 0);
    $("textarea").each(resize);
    $("textarea").keyup(resize).keydown(resize);
}

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

接受的答案工作得很好。但是对于这个简单的功能来说,代码太多了。下面的代码将完成这个任务。

   $(document).on("keypress", "textarea", function (e) {
    var height = $(this).css("height");
    var iScrollHeight = $(this).prop("scrollHeight");
    $(this).css('height',iScrollHeight);
    });

这些答案似乎都不管用。但这个对我很有用: https://coderwall.com/p/imkqoq/resize-textarea-to-fit-content

$('#content').on( 'change keyup keydown paste cut', 'textarea', function (){
    $(this).height(0).height(this.scrollHeight);
}).find( 'textarea' ).change();