设置onInput
以根据scrollHeight
属性调整输入字段的大小...
scrollHeight 值等于元素需要的最小高度,以便在不使用垂直滚动条的情况下适应视口中的所有内容。(来源:以上链接的 MDN Webdocs。)
因此,如果scrollHeight
高于最大值,我们将高度设置为最大值,否则,我们将高度设置为scrollHeight
。
注意:我将其更改为 a textarea
,因为它更自然地适用于从上到下流动的文本(而输入元素不能自然地使用它)。
const tx = document.getElementsByTagName("textarea");
const maxheight = 100;
const normalheight = window.getComputedStyle(tx[0]).getPropertyValue('height').replace("px", "");
for (let i = 0; i < tx.length; i++) {
tx[i].setAttribute("style", "margin-top:-3px;" + "height:" + (tx[i].scrollHeight > maxheight ? maxheight : tx[i].scrollHeight) + "px;overflow-y:hidden;");
tx[i].addEventListener("input", OnInput, false);
}
function OnInput() {
this.style.marginTop = (normalheight - this.style.height.replace("px", "")) + "px";
this.style.height = "auto";
this.style.height = (this.scrollHeight > maxheight ? maxheight : this.scrollHeight) + "px";
}
<div class="text-center textbox-1">
<textarea rows="1"></textarea>
</div>