Can I make a textarea grow with text to a max height?

。_饼干妹妹 提交于 2019-11-30 06:01:12

You can use contenteditable and let the user input in a straight div, here's a demo: http://jsfiddle.net/gD5jy/

HTML

<div contenteditable>
    type here...
</div>

CSS

div[contenteditable]{
    border: 1px solid black;
    max-height: 200px;
    overflow: auto;
}

There's an excellent A List Apart article on this topic: Expanding Text Areas Made Elegant

Alex Ruhl

Here is the JavaScript function

// TextArea is the Id from your textarea element
// MaxHeight is the maximum height value
function textarea_height(TextArea, MaxHeight) {
    textarea = document.getElementById(TextArea);
    textareaRows = textarea.value.split("\n");
    if(textareaRows[0] != "undefined" && textareaRows.length < MaxHeight) counter = textareaRows.length;
    else if(textareaRows.length >= MaxHeight) counter = MaxHeight;
    else counter = 1;
    textarea.rows = counter; }

here is the css style

.textarea {
height: auto;
resize: none; }

and here is the HTML code

<textarea id="the_textarea" onchange="javascript:textarea_height(the_textarea, 15);" width="100%" height="auto" class="textarea"></textarea>

it works fine for me

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