태그 보관물: textarea

textarea 자동 높이 맞추기 Javascript 예제

아래는 textarea에 작성된 내용의 길이에 맞춰 style의 height를 계산하는 예제이다.

function textareaAutoHeight(el) {
    setTimeout(() => {
        el.style.height = 'auto';

        let scrollHeight = el.scrollHeight;
        let outlineHeight = el.offsetHeight - el.clientHeight;

        el.style.height = (scrollHeight + outlineHeight) + 'px';
    }, 0);
}

위 코드는 textarea의 스타일이 box-sizing: border-box;일 때 완벽하게 동작한다.

위 코드에서 중요한 부분은 바깥쪽을 포함한 높이 offsetHeight와 안쪽의 높이 clientHeight의 차를 textarea 높이에 더해준다는 것이다.

만약 이 계산을 포함하지 않으면 textarea에 테두리(border)가 있을 경우에 테두리의 위(border-top-width) + 아래(border-bottom-width) 만큼 손해를 보게 된다.

주의할 점은 border-width 값을 직접 더해주면 안된다. border-width의 단위는 픽셀(px)이 아닐 수도 있다. 그렇기 때문에 element 객체의 offsetHeight – clientHeight 로 테두리의 높이를 구해야 한다.