今天的任务是生成一个高度自适应的textarea,并且也能够设置最小高度和最大高度。
最简单的方法
textarea的属性是overflow:auto;那么若是内容的高度大于textarea自己的高度时,能够把textarea的高度设置成scrollHeightcss
let textarea = document.getElementById('textarea'); textarea.style.height = textarea.scrollHeight + 'px';
这种方法能解决textarea从小变到大的过程。可是有一个问题,当想从大变到小的时候,这个scrollHeight不能反映文字的实际高度,因此这个方法不是很适合。app
高度跟着文字的多少走的,并且不须要动画。
若是不须要设置最小高度,一直是跟着文本的高度走的,能够采用这种方式:
auto-textarea: stackoverflow
这种方式的主要是先把textarea的height设置成auto,而后再设置:动画
textarea.style.height = 'auto'; textarea.style.height = textarea.scrollHeight + 'px';
可是这个设置还有一个问题,若是变化高度时,想要有一个动画过程,这样设置就不行。spa
ant.design用的方式
生成一个无用的textarea,用来计算textarea的高度。debug
let hiddenTextarea; const factors = [ "letter-spacing", "line-height", "padding-top", "padding-bottom", "font-family", "font-weight", "font-size", "text-rendering", "text-transform", "width", "text-indent", "padding-left", "padding-right", "border-width", "box-sizing" ]; export default function calculateNodeHeight(utext){ // debugger; if (!hiddenTextarea) { hiddenTextarea = document.createElement('textarea'); document.body.appendChild(hiddenTextarea); } let cssStyle = window.getComputedStyle(utext); let styleSize = factors.map(n=>{ return n + ':' + cssStyle.getPropertyValue(n) }).join(";") hiddenTextarea.setAttribute('style', styleSize); hiddenTextarea.value = utext.value || utext.placeholder || ''; let height = hiddenTextarea.scrollHeight; hiddenTextarea.value = ''; return { scrollHeight: height } }