HTML textarea 자동 높이 조절

Jmnote (토론 | 기여)님의 2016년 10월 18일 (화) 20:17 판 (210.211.88.240(토론)의 편집을 Jmnote의 마지막 판으로 되돌림)

1 개요

textarea overflow visible
textarea auto resize in html on chrome
textarea 높이 내용물에 맞추기
textarea 자동 크기 조절
<style> textarea {width:300px;overflow:visible;} </style>
<textarea>Hello world</textarea>
IE8에서는 그에 맞게 TEXTAREA의 세로 크기가 늘어난다.
크롬에서는 늘어나지 않고, 대신 스크롤이 생긴다...

2 방법 1: JavaScript

내용물 높이에 맞춰주는 스크립트를 추가하면 크롬에서도 자동맞춤이 된다.

<script>
function resize(obj) {
  obj.style.height = "1px";
  obj.style.height = (20+obj.scrollHeight)+"px";
}
</script>
<textarea onkeyup="resize(this)">Hello world</textarea>

3 방법 2: jQuery

방법 1과 동일하게 jQuery로 구현

<script src="//code.jquery.com/jquery.min.js"></script>
<script>
$(function() {
  $("textarea.autosize").keyup(function () {
    $(this).css("height","1px").css("height",(20+$(this).prop("scrollHeight"))+"px");
  });
});
</script>
<textarea class="autosize">Hello world</textarea>

4 같이 보기

5 참고 자료

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}