簡體   English   中英

使用最大高度限制自動擴展文本區域

[英]Auto-Expand Text Area With Maximum Height Limit

我有一個聊天機器人的文本區域。 當文本區域被填滿時,它想自動向上擴展,它可以擴展的最大高度應該是 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; for (let i = 0; i < tx.length; i++) { tx[i].setAttribute("style", "height:" + (tx[i].scrollHeight > maxheight? maxheight: tx[i].scrollHeight) + "px;overflow-y:hidden;"); tx[i].addEventListener("input", OnInput, false); } function OnInput() { 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM