在输入时调整文本区域的大小 [英] Resize textarea on input
问题描述
我想创建一个自动增长的文本区域,所以我使用了本指南.它运作良好,但是有一个小问题.当您插入大文本并将其删除时,textarea的大小将超过其应有的大小.对于每个插入的字符,其大小都会减小1-2像素,因此,对于几个插入的字符,其高度将再次正确.
I wanted to create a auto-growing textarea, so I used this guide. It works well, but there is a small problem. When you insert large texts and delete them, the textarea has a bigger size than it should have. With every inserted character, the size is reduced by 1-2 px, so with a few inserted characters the height is right again.
要重新创建磨损的scrollHeight,请插入'a \ n b \ n c \ n d \ n e'进入文本区域,现在将其全部删除.textarea保持比现在更大的大小.对于每个插入的字符,textarea都会将其大小调整为正确的值.
To recreate the worng scrollHeight, insert 'a \n b \n c \n d \n e' into the textarea.Now delete all of it. The textarea keeps a bigger size than it needs now. With every inserted character the textarea will adjust its size to the right value.
$("#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
在删除大文本后,如何立即将文本区域调整为尽可能小的值?
How can I get the textarea to resize to the smallest possible value immediately after a big text is deleted?
推荐答案
将其快速重置为 auto
,然后再进行 scrollHeight
并重新进行设置:
Reset it quickly to auto
before going for scrollHeight
and reassagning it:
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>
这篇关于在输入时调整文本区域的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!