所以,我有一个<textarea>
作为用户将输入列表项的表单的一部分。我决定尝试使用一些 jQuery 来扩展 <textarea>
的高度空间被填满。我已经让它以基本形式工作,但我似乎有一个问题,那就是每次 keyup()
事件被调用时,<textarea>
的高度增加,而不是当内容填充它时。这是我的代码:
HTML:
<textarea class="list_header_itemInput" placeholder="Enter an item..."></textarea>
我的CSS:
.list_header_itemInput {
width: calc(100% - 36px);
line-height: 18px;
resize: none;
max-height: 180px;
}
最后,我的 jQuery:
$('.list_header_itemInput').keyup(function() {
$(this).css({ height: ($(this).height() + 2) });
});
我必须在代码中更改哪些内容才能获得预期结果?
最佳答案
您可以将文本区域的高度设置为 1px,然后测量滚动高度(滚动条表示的像素数)。然后将文本区域的高度设置为 (scrollHeight + 1)。
$('.list_header_itemInput').keyup(function() {
this.style.height = "1px";
this.style.height = (this.scrollHeight + 1) + "px";
});
关于jquery - TextArea 根据内容自动调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27828903/