2017-03-02 41 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>

相關問題