【问题标题】:Resize textarea on input在输入时调整文本区域的大小
【发布时间】:2019-09-16 08:48:56
【问题描述】:

我想创建一个自动增长的文本区域,所以我使用了this 指南。它运作良好,但有一个小问题。当您插入大文本并删除它们时,文本区域的大小超出了应有的大小。 每插入一个字符,大小就会减小 1-2 px,因此插入几个字符后高度又是正确的。

要重新创建磨损的 scrollHeight,请插入 'a \n b \n c \n d \n e' 到 textarea 中。现在将其全部删除。 textarea 保持比现在需要的更大的大小。对于每个插入的字符,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

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

【问题讨论】:

    标签: javascript html css textarea


    【解决方案1】:

    在使用 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>

    【讨论】:

      【解决方案2】:

      试试这个会帮助你得到想要的输出。我已经更新了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>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多