Change height of textarea based on number of lines of text in javascript [duplicate]

天大地大妈咪最大 提交于 2019-12-04 14:18:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!