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?
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
来源:https://stackoverflow.com/questions/15844868/can-i-make-a-textarea-grow-with-text-to-a-max-height