본문 바로가기
HTML/CSS

[ HTML / CSS ] 늘어나는 textarea 만들기

by teamnova 2022. 8. 21.
728x90

오늘은 늘어나는 textarea 를 구현해보겠습니다. 즉, 입력한 글자가 늘어남에 따라 textarea 의 높이도 길어지게 하겠습니다.

 

전체 시연 영상은 다음과 같습니다.

 

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

 

먼저 다음과 같이 textarea 요소를 body 태그 안에 작성합니다.

<textarea cols="30" rows="1" name="text" 
oninput='this.style.height = ""; this.style.height = this.scrollHeight + "px"'
style="resize: none; padding: 8px; margin: 20px;"></textarea>

rows="1" 속성으로 인해서 처음 시작 높이는 1줄이 됩니다. 

 

그리고 oninput 이벤트 속성은 사용자가 요소에 정보를 입력하거나 요소의 값이 변경되면 실행됩니다. 즉, textarea 요소에 사용자가 입력을 할 때마다 해당 textarea의 높이는 스크롤높이와 동일하게 되고, 따라서 textarea의 높이는 고정되지 않고 사용자의 줄바꿈에 따라, 혹은 입력값이 늘어나고 줄어들 때마다 달라지게 됩니다. 

 

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

영상에서 보이는 것처럼 입력 내용의 길이에 따라 textarea 길이도 길어지는 것을 확인할 수 있습니다. 하지만 이 상태에서는 입력을 계속 하면 textarea 높이도 계속해서 길어지게 됩니다. 

max-height 스타일 속성을 부여해서 일정 길이 이상으로는 textarea 가 길어지지 않도록 설정해보겠습니다.

 

<textarea cols="30" rows="1" name="text" 
oninput='this.style.height = ""; this.style.height = this.scrollHeight + "px"'
style="resize: none; padding: 8px; margin: 20px; max-height: 100px;"></textarea>

max-height: 100px; 속성 때문에 textarea 길이는 최대 100px 까지만 늘어나고 그 이상 입력할 경우 다음과 같이 textarea 안쪽이 스크롤되게 됩니다.

 

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

 

 

이것을 활용해서 댓글 형태로 만들어보겠습니다.

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>늘어나는 textarea</title>
</head>
<body>

    <div style="display: flex; margin: 20px;">
        <textarea cols="30" rows="1" name="text" 
        oninput='this.style.height = ""; this.style.height = this.scrollHeight + "px"' 
        style="resize: none; padding: 8px; max-height: 100px; margin-right: 10px;"></textarea>
        <button onclick="clickBtn()" style="padding: 4px 6px; height: fit-content">클릭</button>
    </div>
    <div style="margin: 20px; width: 200px;"">
        작성한 내용:
        <!-- white-space: pre-line; 을 사용해서 줄바꿈을 그대로 표시함 -->
        <p style="white-space: pre-line; width: 300px;"></p>
    </div>

    <script>
        const textarea = document.querySelector("textarea");
        const btn = document.querySelector("button");
        const text = document.querySelector("p");

        function clickBtn() {
            text.innerHTML = textarea.value;
            textarea.value = '';
            textarea.style.height = '30px';
        }

    </script>
    
</body>
</html>

 

<textarea>, <button>, <p> 요소가 있습니다. 버튼을 클릭하면 textarea에 입력한 내용을 <p> 의 innerHTML 값으로 설정하는 간단한 구조입니다.

 <button> 의 onclick 속성값으로 clickBtn() 함수가 지정되었으므로 버튼을 클릭하면 clickBtn() 함수가 실행됩니다. 해당 함수의 마지막 코드인 textarea.style.height = '30px'; 를 추가한 이유는 버튼 클릭 후에 textarea 를 초기화시키면서 textarea의 height을 처음과 비슷하게 줄이기 위함입니다. 해당 코드가 없으면 textarea의 길이는 버튼 클릭 이후에 늘어난 길이 그대로 유지됩니다.

 

 

 

참고사이트 :

https://stackoverflow.com/questions/2803880/is-there-a-way-to-get-a-textarea-to-stretch-to-fit-its-content-without-using-php