JS TypeWriter在文本区域中的滚动效果:向上滚动,自动扩展具有最大高度限制的文本区域



我有一个聊天机器人的文本区域。当文本区域被填充时,它想自动向上扩展,它可以扩展的最大高度应该是100px。有办法这样做吗?

.textbox-1{
padding-top:100px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="text-center textbox-1">
<input class="filter-searchbox py-2" type="search" name="search" placeholder="Search" />
</div>

设置onInput以基于scrollHeight属性调整输入字段的大小。。。

scrollHeight值等于元素在不使用垂直滚动条的情况下适应视口中所有内容所需的最小高度。(来源:以上链接的MDN Webdocs。(

因此,如果scrollHeight高于最大值,我们将高度设置为最大值,否则,我们将身高设置为scrollHeight

注意:我把它改成了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>

最新更新