javascript 根据javascript中的文本行数更改textarea的高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4516435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change height of textarea based on number of lines of text in javascript
提问by Web_Designer
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 中的文本更改为多行文本,则 textarea 将在自身上放置一个滚动条,而不是更改其高度以适应行数。
<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>
回答by JURU
<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.
调整“32”以匹配行高留作练习。

