2020.12.06

DD·2020년 12월 5일
0

개인적으로 뿌듯한 리팩토링..?

textarea의 기본 높이 200 스크롤 없음, 그 이상 늘어나면 그에 맞게 카드가 커지다가 400이 되면 멈추고 스크롤이 생기는 형태로 만들 생각이었다.

처음에 어떻게 자동으로 textarea 크기를 조절하나 찾아보다가 발견하고
단순 조절 뿐 아니라 각 구간마다 overflow를 조절하거나 높이를 계산하거나 해야한다고 생각해서 정말... 개떡같이 코드를 써내려갔다.

let currentHeight = target.scrollHeight;
    if (currentHeight <= minHeight) {
      console.log("~200");
      target.style.cssText = "height: auto; padding: 0";
      target.style.cssText = `height: ${minHeight}px`;
    } else if (currentHeight > minHeight && currentHeight < maxHeight) {
      console.log("200~400");
      target.style.cssText = "height: auto; padding: 0";
      target.style.cssText = `height: ${currentHeight}px`;
    } else if (currentHeight >= maxHeight) {
      console.log("400~");
      target.style.cssText = "height: auto";
      currentHeight = target.scrollHeight;
      if (currentHeight >= maxHeight) {
        target.style.cssText = `height: ${maxHeight}px; overflow: auto`;
      } else {
        target.style.cssText = `height: ${currentHeight}px`;
      }
    }
    currentHeight = target.scrollHeight;

와아 ... 정말 못 짰다 ㅋㅋ ... 일단 생각나는대로 으아아아 코딩하고
적당히 구현 된 후에 발생하는 문제나 가만히 쳐다보니 왜 이렇게 했지 싶어서 다시 코딩했다

target.style.height = "1px";
    if (target.scrollHeight >= 400) {
      target.style.cssText = `height: 400px; overflow: auto;`;
    } else {
      target.style.height = `${target.scrollHeight}px`;
    }
  });

최종 리팩토링한 코드... 이보다 더 나은 방법도 있겠지만.. 정말 시-원하다

일단 원리는 textarea의 높이를 1px로 만든다. 그 순간 scrollHeight가 곧 텍스트의 높이가 된다. 그렇게 높이를 구해서 textarea의 높이에 할당하면 텍스트 길이와 딱맞는 높이가 부여된다..
=> 다음날 확인해보니 1px로 바꿀 필요가 없었다 scrollHeight의 정확한 정의는

Element.scrollHeight 읽기 전용 속성은 요소 콘텐츠의 총 높이를 나타내며, 바깥으로 넘쳐서 보이지 않는 콘텐츠도 포함합니다.

이다. 즉 1px로 줄여서 생기는 스크롤의 길이와 상관없다.. 뭔가 이름에 맞지 않으면서 맞는 느낌... 이 오해때문에 text의 길이가 늘어나면 textarea의 길이가 늘어나는건 되는데 반대로 줄어들지 않는 문제가 해결되지 않았다.

profile
기억보단 기록을 / TIL 전용 => https://velog.io/@jjuny546

0개의 댓글