Geh*_*net 4 html javascript css textarea
我想创建一个自动增长的 textarea,所以我使用了这个指南。它运行良好,但有一个小问题。当您插入大文本并删除它们时,textarea 的大小比它应该有的要大。每插入一个字符,尺寸就会减少 1-2 像素,所以插入几个字符后,高度又恢复了。
要重新创建磨损的滚动高度,请将 'a \n b \n c \n d \n e' 插入文本区域。现在将其全部删除。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>");
});Run Code Online (Sandbox Code Playgroud)
#message-box {
resize: none;
width: 400px;
min-height: 20px;
padding: 5px;
overflow: hidden;
box-sizing: border-box;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="message-box"></textarea>Run Code Online (Sandbox Code Playgroud)
如何在删除大文本后立即将 textarea 调整为可能的最小值?
auto在进行scrollHeight并重新分配之前快速将其重置为:
const $mBox = $("#message-box");
$mBox.on('input', function() {
$(this).height('auto');
$(this).height($(this).prop('scrollHeight'));
}).trigger('input');Run Code Online (Sandbox Code Playgroud)
#message-box {
resize: none;
width: 100%;
box-sizing: border-box;
padding: 5px;
}Run Code Online (Sandbox Code Playgroud)
<textarea id="message-box"></textarea>
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>Run Code Online (Sandbox Code Playgroud)