He creado un elemento de área de texto de expansión automática que crece dinámicamente en función del contenido de texto que contiene, lo que funciona muy bien. Hago esto mirando la altura de desplazamiento y luego agregando esto a la altura del área de texto.
El problema que tengo es cuando cargo texto en la misma área de texto en la carga inicial a través de la propiedad de valor: vuelve a su altura inicial y solo se expande automáticamente cuando me enfoco en el área de texto y presiono Intro, lo que significa que está recortando mucho el contenido (especialmente cuando se trata de artículos de varias líneas).
He estado tratando de encontrar una solución por un tiempo y no he logrado encontrar una solución hasta el momento. ¿Hay alguna manera de determinar la altura de desplazamiento del contenedor como si el usuario hubiera escrito algo en el montaje para expandir el área de texto a la misma altura?
Editar: disculpas por la confusión, el problema surge cuando recuerdo el mismo texto que se ingresó desde una base de datos en el mismo campo de texto
(fotos agregadas para demostrar mi problema)
Fotos agregadas: texto cuando se agrega en el área de texto
(en la segunda imagen, puede ver que el área de texto ha vuelto a su altura original después de que el texto se guardó en una base de datos y se volvió a inyectar en la misma área de texto)
$("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>Esto debería funcionar:
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>