Html 我可以让 textarea 随文本一起增长到最大高度吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15844868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:16:25  来源:igfitidea点击:

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

htmlcsstextarea

提问by Darkenwolf

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?

我正在做一个项目,其中我的 div 中有各种大小的数据。当用户点击其中一个 div 时,它需要变成一个可编辑的 textarea。宽度是恒定的,但我希望高度从原始 div 的高度开始,然后在添加滚动条之前增长到最大高度。那可能吗?

回答by Sandro Paganotti

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

您可以使用contenteditable并让用户直接输入div,这是一个演示:http: //jsfiddle.net/gD5jy/

HTML

HTML

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

CSS

CSS

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

回答by Alex Ruhl

Here is the JavaScript function

这是 JavaScript 函数

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

这是css样式

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

and here is the HTML code

这是 HTML 代码

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

it works fine for me

这对我来说可以

回答by olivergeorge

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

有一篇关于这个主题的优秀 A List Apart 文章:扩展文本区域使优雅