2009. 7. 8. 08:48

TextArea 크기 자동 맞추기

아래는 TextArea 의 텍스트 내용에 따라 크기를 자동 조절하여 스크롤바를 없애는 예이다.

업데이트 : 2009-07-08

스크롤바 크기를 비교하여 복잡하게 하는 것보다, 그냥 스타일 쉬트에 다음을 적용하는게 훨씬 쉽다.

overflow:visible;


아래는 프로그래밍적으로 해결.

<style type="text/css">

.NoScroll {

        overflow:hidden;  

    }

</style>

 

<script type="text/javascript" language="javascript">

function onFitSizeOfTextArea()

    {

        var textArea = event.srcElement;

        while( textArea.clientHeight < textArea.scrollHeight )

        {

            textArea.rows = textArea.rows + 1;

        }

        textArea.className = "NoScroll";

    }

</script>

 

<textarea cols="50" rows="3" onclick="onLoadTextArea();" >Some long text</textarea>


컨셉은 굉장히 단순하다. Textarea 의 스크롤 높이가 Textarea 의 클라이언트 높이보다 작거나 같을때까지 row를 하나씩 증가시키는 것이다. onload 라는 이벤트 핸들러가 없어서 테스트는 onClick 이벤트에다가 핸들러를 추가했는데 이걸 응용하여 어떻게든 적용할 수 있을 것이다.

또한, NoScroll 스타일을 적용하여 스크롤을 없앴다.

CSS 와 프로그래밍에는 각기 장점이 있으므로 경우에 따른 방법을 사용하자.