2017-03-02 28 views
0

此问题可能对此网站不存在,但我不知道在哪里寻找这样的内容,所以我很抱歉,如果是这样。如何将textarea扩展为其内容并禁用使用CSS和jQuery进行手动调整大小

所以我在Google窗体上制作了一个带有长答案问题的dummy test form,我试图弄清楚文本区域如何随其内容扩展,但禁用了调整大小。由于我增加了超过300个字符的文本数量,最后一行文本和textarea的底部之间出现了差距,粘贴文本多次只增加了空间量。我的猜测是,谷歌计算文本的aproximative高度使用平均的字符拟合在一条线上的字符数量与textarea框中写入的字符数量。

所以我想知道是否有更准确地检测在textarea线的数量和谷歌的形式一样调整它的高度的方式

我想(但也许更好?):

  1. 也许每个字母都有一个精确的单独宽度和 然后计算下一个字母是否适合该行。
  2. 也许有一个隐藏的视图div具有相同的宽度和相同的 文本样式并将文本快速复制到div,然后将 div的偏移高度复制到textarea?
  3. 也许我想念你们可能知道的东西?

让我知道你的tough!!

+1

你怎么样计算行数textarea的身高[这](http://stackoverflow.com/questions/2035910/how-to-get-the-number-of -lines-in-a-textarea)可能会有所帮助,至于禁用调整大小请看看[this](http://stackoverflow.com/questions/5235142/how-to-disable-resizable-property-of-textarea ) – mbeso

+0

我的'textarea'有一个固定的'width'和'height',并且'resize:none;'所以我不能使用像height这样的东西。我正在计划使用这些信息更新身高。在引用帖子中使用的String.prototype.lineCount()仅返回1.我希望行数包括通过包装文本创建的行。就像我在Google表格上的示例 –

+0

这个JSfiddle可能是一个很好的解决方案! http://jsfiddle.net/Mottie/PfD7L/100/ –

回答

0

这样做使用jQuery的技巧,如果有人正在寻找一个可靠的解决方案,可以站立在一个万亿字符和处理高度在不到5秒钟!

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

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

 
\t \t //Make the height of the <textarea> 0 to be able to get an "adjusted to content" read of the .scrollHeight 
 
\t \t $(ta).height(0); 
 
\t \t //Make the height of the <textarea> as tall as the .scrollHeight as it has wrapped the content of the text area 
 
\t \t $(ta).height(ta.scrollHeight-(padAndBordHeight)); 
 
\t \t $(ta).parent().find("strong").toggleClass("visible",ta.scrollHeight>ta.offsetHeight); 
 
\t \t //log the amount of lines in the console /!\ 20 is my line height /!\ 
 
\t \t /*console.log("There are "+Math.ceil($(ta).height()/20)+" lines in the current textarea");*//*my line heigh is 34*/ 
 
\t } 
 
function textareaBlur(ta){ 
 
\t $(ta).height(20); 
 
\t $(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>

相关问题