根据文本行数改变Javascript文本域的高度

3
这是一个可能重复的问题:

可能重复:
使用原型自动调整文本区域的大小

如何根据用户输入的文本行数来更改文本区域的高度?

例如,如果用户在下面的文本区域中更改文本以超过一行,则文本区域会在自身上放置滚动条而不是更改其高度以适应文本行数。

<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>

2
@FelixKling 只有在我们假设 OP 使用原型的情况下,才能得出这个结论,而他从未提到过。 - Chad
1个回答

4
<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';
}

调整“32”以匹配行高,留作练习。


不起作用:http://jsfiddle.net/MYrG2/ - Web_Designer
JSFiddle的问题,不是脚本的问题。来自Chrome的错误信息:“尝试访问URL为http://jsfiddle.net/MYrG2/的框架,但其来源为http://fiddle.jshell.net/MYrG2/show/。域名、协议和端口必须匹配。”跨站点脚本错误,多么古雅。 - JURU
1
哎呀,小补充一下:为了解决在Webkit上的问题,应该在文本区域的样式中添加"overflow-y: hidden"。 - JURU
5
贬低性评论需被踩。 - Will Shaver
不要忘记调整填充(padding)。看起来scrollHeight包含顶部和底部的填充(padding)。 - Phil LaNasa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接