在你的初始化,把下面以防止出現錯誤(這是什麼讓這不到3 00個字符):
oldVal = "";
如果使用等寬字體,並且知道適合在一排字符的數量,每個信打的時候,你可以做到以下幾點上鍵入每個字符....這是假設你可以在每行適合22個字符...
// save the element as variable, just to access without typing as much
elem = document.getElementById('txtpostSearch');
//if the length is above 300, set it back to what the value was before
if(elem.length > 300){
elem.value = elem.value.substring(0, 300);
}
// the length of the contents of the textarea
len = elem.value.length;
// the new number of rows in the textarea
// it is the number of rows completely filled by text, plus two
// plus two makes room for the row currently typing in, and one more empty row
rows = Math.floor(len/22) + 2;
// sets the height as the number of rows in units of font size
elem.style.height = rows + 'em';
//store the value in case the next length is too large
oldVal = elem.value;
我做了一個小提琴:https://jsfiddle.net/5w7gogqt/
這撥弄使用一個叫做ProFont(如果你沒有它的字體,小提琴默認爲普通等寬),無論您使用哪種操作系統或瀏覽器,它總是具有一定的大小。你總是可以爲你的領域使用一個webfont,然後人們使用這個字體,即使他們沒有它。
檢查了這一點:http://stackoverflow.com/a/12269010/1267304 – DontVoteMeDown
的可能的複製[簡單的jQuery textarea的擴展,以適應內容(HTTP ://stackoverflow.com/questions/12268921/simple-jquery-textarea-expand-to-fit-content) – DontVoteMeDown
@DontVoteMeDown:我想算的性格也 – Sri