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

对着背影说爱祢 提交于 2019-11-29 05:23:06

问题


I'm working on a project where I have data in divs that can be various sizes. When a user clicks on one of the divs, it needs to turn into an editable textarea. The width is constant, but I'd like the height to start as the height of the original div and then grow to a max height before adding a scrollbar. Is that possible?


回答1:


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



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/15844868/can-i-make-a-textarea-grow-with-text-to-a-max-height

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