简体   繁体   中英

How to auto resize the text area element on load?

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?

Edit: Apologies for the confusion, the issue comes when I recall the same text that was entered from a database into the same textfield

(added photos to demonstrate my issue)

Added photos: Text when added in textarea

Same text on load/mount

(on the second image, you can see that the text area has gone back to it's original height after the text has been saved to a database and injected back into the same 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>

This should work:

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM