簡體   English   中英

如何在加載時自動調整文本區域元素的大小?

[英]How to auto resize the text area element on load?

我創建了一個自動擴展的 textarea 元素,它根據其中的文本內容動態增長,效果很好。 我通過查看滾動高度然后將其添加到文本區域的高度來做到這一點。

我遇到的問題是,當我通過 value 屬性在初始加載時將文本加載到相同的 textarea 時 - 它會恢復到初始高度,並且只有在我專注於 textarea 並按 Enter 時才會自動擴展,這意味着它會裁剪掉很多內容(特別是在涉及多行項目的情況下)。

一段時間以來,我一直在嘗試想出一個解決方法,但到目前為止我還沒有找到解決方案。 有沒有一種方法可以確定容器的滾動高度,就好像用戶在 mount 上鍵入了一些東西以將 textarea 擴展到相同的高度?

編輯:為混亂道歉,當我回憶起從數據庫輸入到同一個文本字段中的相同文本時,問題就出現了

(添加照片以證明我的問題)

添加的照片:在 textarea 中添加時的文本

加載/安裝上的相同文本

(在第二張圖片中,您可以看到在將文本保存到數據庫並注入回同一文本區域后,文本區域已恢復到原來的高度)

 $("textarea").height( $("textarea")[0].scrollHeight );
 textarea { width: 400px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <textarea> I have created an auto expanding textarea element that dynamically grows based on the text content within it which works great. I do this by looking at the scroll height and then adding this to the height of the textarea. The problem I have is when I load text into the same textarea on initial load via the value prop - it reverts back to it's initial height and only auto expands when I focus in on the textarea and hit enter which means it's cropping out a lot of the content (especially where multi-line items are concerned). I've been trying to come up with a workaround for a while and I haven't managed to find a solution as of yet. Is there a way I can determine the scroll height of the container as if the user had typed something on mount to expand the textarea to the same height? </textarea>

這應該有效:

 let textarea = document.querySelector('textarea') function auto_grow(element){ element.style.height = (element.scrollHeight) +"px" }
 textarea{ resize: none; overflow: hidden; height: 1000px; font-size: 15px; line-height: 1.5em; }
 <textarea oninput = "auto_grow(textarea)"></textarea>

暫無
暫無

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

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