getelementbyid에서 classname으로 변경 질문 채택완료
textarea 의 값에 다라 높이가 자동으로 조절되는 것을 적용하고 있습니다.
id 방식으로 사용하려고 했으나 wr_content 뿐만 아니라 wr_subject_[i], wr_[i] 이런식으로 id값이 1씩 증가하고 있는데요. get id는 한개의 값만 담는다고 해서 하단 코드는 다른곳엔 적용될 수 없더라고요.
그래서 className 을 활용해서 바꿔보려하는데 단순히 id 영역만 교체한다고 해서 자꾸 오류가 나네요 ㅠㅠ 도움 부탁드립니다
Copy
function autoResize() {
for (var i = 0; i <= 20; i++) {
let textarea = document.getElementById("wr_content_" + i);
textarea.style.height = "0px";
let scrollHeight = textarea.scrollHeight;
let style = window.getComputedStyle(textarea);
let borderTop = parseInt(style.borderTop);
let borderBottom = parseInt(style.borderBottom);
textarea.style.height = (scrollHeight + borderTop + borderBottom)+"px";
}
}
window.addEventListener("load", autoResize);
window.onresize = autoResize;
답변 1개
채택된 답변
+20 포인트
2년 전
Copy
<script>
function autoResize() {
this.style.height = "0px";
let scrollHeight = this.scrollHeight;
let style = window.getComputedStyle(this);
let borderTop = parseInt(style.borderTop);
let borderBottom = parseInt(style.borderBottom);
this.style.height = (scrollHeight + borderTop + borderBottom)+"px";
}
function init() {
Array.from(document.getElementsByClassName('ta')).forEach((el, i) => {
el.addEventListener('input', autoResize, false);
el.addEventListener('focus', autoResize, false);
});
}
window.addEventListener("load", init);
// window.onresize = autoResize;
</script>
<textarea class="ta"></textarea>
<textarea class="ta"></textarea>
<textarea class="ta"></textarea>
로그인 후 평가할 수 있습니다
답변에 대한 댓글 3개
2년 전
답변 감사합니다. 베르만님. 소스를 적용해보았는데 페이지가 새로고침될 당시에는 textarea높이를 계산을 못하고 한줄로 나오고 마우스로 클릭하여 활성화가 되는 순간 높이값이 변동되네요. 제 설명이 조금 부족했던 탓인지 구현하고자 하는 것은 글이 수정되었을 때 즉 비활성화 상태일때도 높이값을 자동으로 가져오고싶은것입니다.
2년 전
[code]
...
el.addEventListener('input', autoResize, false);
el.addEventListener('focus', autoResize, false);
autoResize.call(el);
...
[/code]
...
el.addEventListener('input', autoResize, false);
el.addEventListener('focus', autoResize, false);
autoResize.call(el);
...
[/code]
댓글을 작성하려면 로그인이 필요합니다.
답변을 작성하려면 로그인이 필요합니다.
로그인