[英]Fit textarea width to the longest line of text
How do I make a textarea increase its WIDTH while the user is typing. 用户输入时,如何使文本区域增加WIDTH。 Basically I need the WIDTH of the textarea to be only to the length of the longest line.
基本上,我需要将textarea的WIDTH设置为最长行的长度。
This is what I came up with. 这就是我想出的。 But when the user hits ENTER still the width increases.
但是,当用户按下ENTER键时,宽度仍然增加。 How do I make the textarea to fit only to the size of its text?
如何使文本区域仅适合其文本大小?
$(document).on("click blur keyup", ".fT", function() {
var newWidth = ($('#tfd').val().length)*10;
$('#tfd').width(newWidth);
});
As @progrAmmar mentioned, $('#tfd').val().length
measures the total length for your text, not the width of the longest line. 正如@progrAmmar所提到的,
$('#tfd').val().length
tfd $('#tfd').val().length
衡量文本的总长度,而不是最长行的宽度。
In fact your newWidth
is just an approximation and will not be correct at all if a user types non ASCII characters. 实际上,您的
newWidth
只是一个近似值,如果用户键入非ASCII字符,则将根本不正确。
One way to approxmiate the length is to place a pre
element somewhere, set visibility:hidden
and font-size
and font-family
the same as your textarea, and update this element with the new content whenever the user types. 近似长度的一种方法是将
pre
元素放置在某处,设置visibility:hidden
, font-size
和font-family
与您的文本区域相同,并在用户键入时使用新内容更新该元素。
By measuring this pre
element's width you can get a good approximation for the text. 通过测量该
pre
元素的宽度,您可以很好地近似文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.