问题
Possible Duplicate:
Autosizing textarea using prototype
How do I change the height of a text area based on the number of lines of text that the user puts into it?
For the example below if the user changed the text in the textarea to more than one line of text then the textarea would put a scroll bar on itself rather than changing its height to fit the number of lines.
<textarea>
This is the default text that will be displayed in the browser. When you change this text and add more lines to it the browser will not change the height of the textarea that this text is in rather it will add a scroll bar, which is not what I want.
<textarea>
回答1:
<textarea onkeyup="autoSize(this);"></textarea>
function autoSize(ele)
{
ele.style.height = 'auto';
var newHeight = (ele.scrollHeight > 32 ? ele.scrollHeight : 32);
ele.style.height = newHeight.toString() + 'px';
}
Adjusting "32" to match line-height is left as an exercise.
来源:https://stackoverflow.com/questions/4516435/change-height-of-textarea-based-on-number-of-lines-of-text-in-javascript