Cuando ejecute este fragmento, verá lo siguiente (al menos en Chrome 97.0.4692.71):
clientHeight y scrollHeight son más de lo necesario para 1 línea.line-height no está undefined a menos que se establezca explícitamente. La configuración line-height afecta los valores iniciales clientHeight y scrollHeight .clientHeight o scrollHeight . Parecen inicializarse con suficiente espacio para 2 líneas.scrollHeight , como se esperaba, pero no es igual a textHeight .scrollHeight aumente pero no se agregan saltos de línea al texto (es decir, textHeight no cambia). ¿Cuáles son los cálculos utilizados para llegar a los valores de clientHeight y scrollHeight observados?
const textarea = document.querySelector('textarea'); document.addEventListener('DOMContentLoaded', () => { resize(textarea); }); textarea.addEventListener('input', (inputEvent) => { resize(inputEvent.target); }); function resize(o) { const lines = getLines(o); const fontSize = getCSSIntegerValue(o, 'font-size'); const padding = getCSSIntegerValue(o, 'padding'); const borderWidth = getCSSIntegerValue(o, 'border-width'); const textHeight = fontSize * lines; console.log('fontSize=%d, lines=%d, padding=%d, borderWidth=%d, textHeight=%d, clientHeight=%d, scrollHeight=%d', fontSize, lines, padding, borderWidth, textHeight, o.clientHeight, o.scrollHeight); } function getCSSIntegerValue(o, property) { const computedValues = window.getComputedStyle(o); const propertyValue = computedValues.getPropertyValue(property); return parseInt(propertyValue.replace(/\D/g, '')); } function getLines(o) { const lines = o.value.split(/\r|\r\n|\n/); return lines.length; } textarea { all: unset; background-color: #ddd; overflow-y: hidden; overflow-x: hidden; overflow-wrap: break-word; font-size: medium; } <textarea></textarea>line-height , a menos que se defina, usará la hoja de estilo del agente de usuario (típicamente 1.2 para navegadores de escritorio, según MDN ). Con esa información, los resultados deberían tener más sentido.
clientHeight siempre es 2 * line-height .
scrollHeight es line-height * lines .