在你的初始化,把下面以防止出现错误(这是什么让这不到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