Estoy tratando de cambiar el ancho de un div según el contenido del div:
Digamos que inicialmente el div tiene un ancho de 100 px, quiero que permanezca en ese ancho hasta que el usuario haya llenado 90 px con texto.
Cuando esto llegue, el ancho del div debe incrementarse en un valor fijo. si el usuario escribe aún más (190 px), el div volverá a tener su ancho incrementado. Intenté usar clientWidth del div de esta manera:
get style(): string { if (!this.el) { return ` width: 100px; line-height: ${DEFAULT_HEIGHT}px; max-height: inherit; `; } let divWidth = 100; const maxWidth = window.innerWidth - SCROLLBAR_WIDTH; while (this.el.clientWidth > divWidth * 0.9 && divWidth < maxWidth) { const width = width + 100 if (width > maxWidth) { break; } divWidth = width; } return ` width: ${divWidth}px; line-height: ${DEFAULT_HEIGHT}px; max-height: inherit; `; }pero compara el ancho del div consigo mismo y no el contenido del div.
Gracias por adelantado,
Puede relacionarse con esta respuesta para obtener el ancho del contenido: https://stackoverflow.com/a/47224153/12933115
Mi recomendación es que uses dos DIV anidados como este:
<div id="container"> <div id="content"></div> </div> <input id="txtBox" /> El div#container tendría un tamaño fijo, mientras que el div#content no.
#container { width: 100px; } #content { max-width: fit-content; max-width: -moz-fit-content; /* For Mozilla Firefox */ }Ahora, detecta la escritura en lugar del ancho. Luego, verifica el ancho del DIV interno dentro del detector de eventos.
const input = document.getElementById("txtBox"); input.addEventListener("input", () => { // Check the width of the inner DIV (#content) here... // If the width of the inner width exceeds your limit, then you change the width // of the container DIV (#container). });Lo anterior fue una explicación general. Descubrirá cómo aplicar esto de acuerdo con sus necesidades.