英文:
How can I switch textarea to multiline when overflown with text?
问题
我想要有任何输入(在这种情况下,我猜是
英文:
I'd like to have any input ( <textarea> element in this case I guess) like in Whatsapp or Telegram. It should be 1 line by default. But when a line is overflown with text it should become 2-line textarea. And when the second line is also overflown, it should become a 3-line textarea. And vice versa.
I have no idea how to implement this. My first thought was to count input text characters and then change the lines depending on the amount of symbols. But then I realized it was a bad idea because different characters have different width. And a string "wwwwwwwwww" is wider than "iiiiiiiiii" when the font is Arial, but both strings have 10 characters.
答案1
得分: 0
根据scrollHeight属性更改textarea元素的高度。以下是使用jQuery的示例。如果仅用于单个textarea输入,可以简化代码。
$("#divContainingAutoSizingTextareas").on("keyup", "textarea:focus", function (e) {
var textarea = $(":focus");
textarea.height(textarea.prop("scrollHeight") - 12);
})
以下是一个不使用jQuery的示例。重置高度的目的是在删除内容时使textarea缩小。+2的目的是调整可能导致不一致结果的任何样式 - 您可以轻松确定尺寸是否在一致调整,并相应地进行调整。
document.getElementById("autoexpand").addEventListener("keyup", function () {
var textarea = document.getElementById("autoexpand");
textarea.style.height = "34px";
textarea.style.height = textarea.scrollHeight + 2 + "px";
})
英文:
Change the height of the textarea element based on the scrollHeight property. Here is an example using jQuery. It could be simplified if used for a single textarea input.
$("#divContainingAutoSizingTextareas").on("keyup", "textarea:focus", function (e) {
var textarea = $(":focus");
textarea.height(textarea.prop("scrollHeight") - 12);
})
Here is an example without jQuery. The purpose of resetting height is to cause the textarea to shrink when content is removed. The purpose of the + 2 is to adjust for any styling that may make inconsistent results -- you can easily determine if the sizing is adjusting consistently and adjust accordingly.
document.getElementById("autoexpand").addEventListener("keyup", function () {
var textarea = document.getElementById("autoexpand");
textarea.style.height = "34px";
textarea.style.height = textarea.scrollHeight + 2 + "px";
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论