如何使用 CSS 和 jQuery 将文本区域扩展到其内容并禁用手动调整大小

How to expand a textarea to its content and disable manual resizing using CSS and jQuery

这个问题对于这个网站来说可能是错误的,但我不知道在哪里可以找到这样的东西,所以如果是的话,我很抱歉。

所以我在 Google 表单上制作了一个 dummy test form 长答案问题,我试图弄清楚文本区域如何随其内容扩展,但调整大小被禁用。

由于我增加了文本的数量,所以超过 300 个 lorem ipsum 字符,文本的最后一行和 textarea 的底部之间出现了间隙,粘贴文本几次只增加了数量space。我的猜测是,google 计算文本的近似高度时使用与 textarea 框中写入的字符数相比适合一行的平均字符数。

所以我想知道是否有一种方法可以更准确地检测 textarea 中的行数并像 google 表格一样调整它的高度(但也许更好?)

我在想:

  1. 也许可以精确测量div等宽和等宽的每个字母 然后计算下一个字母是否适合该行。?
  2. 也许有一个隐藏的视图 div 具有相同的宽度和相同的 文本样式并快速将文本复制到 div 然后复制 div 文本区域的偏移高度?
  3. 也许我漏掉了一些你们可能知道的东西?

告诉我你的难处!

如果有人正在寻找一种可靠的解决方案,可以在不到 5 秒的时间内处理一百万个字符并处理高度,那么使用 jQuery 就成功了!

$('textarea').on('input propertychange paste', function() {
  adjustTextareaHeight(this);
 });
function adjustTextareaHeight( ta ) {
  //Get the height of any padding and border that's computed by jQuery in .height
  var  padAndBordHeight = $(ta).outerHeight()-$(ta).height();

  // because the scrollbar can cause calculation problems
  $(ta).css( "overflow", "hidden" );

  //Make the height of the <textarea> 0 to be able to get an "adjusted to content" read of the .scrollHeight
  $(ta).height(0);
  //Make the height of the <textarea> as tall as the .scrollHeight as it has wrapped the content of the text area
  $(ta).height(ta.scrollHeight-(padAndBordHeight));
  $(ta).parent().find("strong").toggleClass("visible",ta.scrollHeight>ta.offsetHeight);
  //log the amount of lines in the console /!\ 20 is my line height /!\
  /*console.log("There are "+Math.ceil($(ta).height()/20)+" lines in the current textarea");*//*my line heigh is 34*/
 }
function textareaBlur(ta){
 $(ta).height(20);
 $(ta).parent().find("strong").toggleClass("visible",ta.scrollHeight>ta.offsetHeight);
}
$('textarea').each(function() {
adjustTextareaHeight(this);
})
/* textarea needs a line-height for the javascript to work */
#ta, #foo {
  display:block;
    width: 300px;
    line-height: 20px;
    height:20px;
    resize:none;
    overflow:hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="lines">...</div>

<textarea id="ta" rows="1" onfocus="adjustTextareaHeight(this);" onblur="textareaBlur(this)"></textarea>
<textarea id="foo" rows="1" onfocus="adjustTextareaHeight(this);" onblur="textareaBlur(this)"></textarea>