调整输入文本区域的大小

Resize textarea on input

我想创建一个自动增长的文本区域,所以我使用了 this 指南。它运行良好,但有一个小问题。当您插入大文本并删除它们时,textarea 的大小比它应有的大。 每插入一个字符,尺寸就会缩小 1-2 px,所以插入几个字符后,高度又会恢复正常。

要重新创建磨损的 scrollHeight,请将 'a \n b \n c \n d \n e' 插入 textarea.Now 并删除所有内容。 textarea 保持比现在需要的更大的尺寸。每插入一个字符,文本区域都会将其大小调整为正确的值。

$("#message-box").on('input', function() {
  var scroll_height = $("#message-box").get(0).scrollHeight;
  $("#message-box").css('height', scroll_height + 'px');

  $("body > p").remove();
  $("body").append("<p>ScrollHeight: " + scroll_height + "</p>");
});
#message-box {
  resize: none;
  width: 400px;
  min-height: 20px;
  padding: 5px;
  overflow: hidden;
  box-sizing: border-box;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="message-box"></textarea>

Here is the example in CodePen

如何在删除大文本后立即将文本区域调整为尽可能小的值?

在前往 scrollHeight 并重新分配之前,快速将其重置为 auto

const $mBox = $("#message-box");

$mBox.on('input', function() {
  $(this).height('auto');
  $(this).height($(this).prop('scrollHeight'));
}).trigger('input');
#message-box {
  resize: none;
  width: 100%;
  box-sizing: border-box;
  padding: 5px;
}
<textarea id="message-box"></textarea>

<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>

试试这个会帮助你得到想要的输出。我已经更新 resize.

的高度

messagebox();

function messagebox() {
  var text = $('.message-box');

  text.each(function() {
    $(this).attr('rows', 1);
    resize($(this));
  });

  text.on('input', function() {
    resize($(this));
  });

  function resize($text) {
    $text.css('height', 'auto');
    $text.css('height', $text[0].scrollHeight + 'px');
  }
}
.message-box {
  resize: none;
  width: 400px;
  min-height: 20px;
  padding: 5px;
  overflow: hidden;
  box-sizing: border-box;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="message-box"></textarea>