-1

我有一个聊天机器人的文本区域。当文本区域被填满时,它想自动向上扩展,它可以扩展的最大高度应该是 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>

4

1 回答 1

1

设置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>

于 2021-12-28T17:03:44.990 回答