【发布时间】:2021-02-17 10:53:07
【问题描述】:
有很多 StackOverflow 的自动高度文本区域示例。一个例子是这样的:
https://stackoverflow.com/a/24676492/1634905
<textarea oninput="auto_grow(this)"></textarea>
textarea {
resize: none;
overflow: hidden;
min-height: 50px;
max-height: 100px;
}
function auto_grow(element) {
element.style.height = "auto";
element.style.height = (element.scrollHeight)+"px";
}
是否有类似的解决方案也包含自动宽度?基本上都是自动宽度和自动高度?
当我尝试以类似方式检索element.scrollWidth 时,它继续为我提供文本区域的原始宽度。
https://jsfiddle.net/on7zasd3/
编辑:
我想我明白了。 (Ps,我不知道为什么在 StackOverflow 上之后代码格式被破坏了?)
-
我必须在文本区域指定
cols="1" -
我还必须执行
element.style.width = "auto";并将纹理的宽度设置为在执行高度auto之前。 -
Textarea 还需要
white-space: nowrap;CSS:函数自动增长(元素){ element.style.width = "自动"; console.log(element.scrollHeight+", "+element.scrollWidth) element.style.width = (element.scrollWidth)+"px";
element.style.height = "auto"; console.log(element.scrollHeight+", "+element.scrollWidth) element.style.height = (element.scrollHeight)+"px";}
文本区域 { 调整大小:无; 溢出:隐藏; 最小高度:30px; 最小宽度:30px; 空白:nowrap; }
【问题讨论】:
标签: javascript html css textarea