我創建了一個自動擴展的 textarea 元素,該元素根據其中的文本內容動態增長,效果很好。我通過查看滾動高度然后將其添加到 textarea 的高度來做到這一點。
我遇到的問題是,當我通過 value prop 在初始加載時將文本加載到同一個 textarea 時 - 它會恢復到它的初始高度,并且只有當我專注于 textarea 并按回車鍵時才會自動擴展,這意味著它會裁剪出很多內容(尤其是涉及多行專案的情況)。
一段時間以來,我一直試圖想出一種解決方法,但到目前為止我還沒有找到解決方案。有沒有一種方法可以確定容器的滾動高度,就好像用戶在 mount 上輸入了一些東西以將 textarea 擴展到相同的高度?
編輯:為混淆道歉,當我回憶起從資料庫輸入到同一個文本欄位的相同文本時,問題就出現了
(添加照片以證明我的問題)
添加的照片: 添加到 textarea 時的文本
加載/掛載上的相同文本
(在第二張圖片上,您可以看到在將文本保存到資料庫并注入到同一個文本區域后,文本區域已經恢復到原來的高度)
uj5u.com熱心網友回復:
$("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>
uj5u.com熱心網友回復:
這應該有效:
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/363228.html
標籤:javascript html css 反应
上一篇:如何讀取JSON陣列
下一篇:禁用按鈕直到功能完成
