오늘의 정리

1. 스크롤을 내릴 때 transparent => 색상이 변하는 기능을 구현하기

스크롤 위치가 0일때
스크롤 위치가 header의 높이를 넘었을 때

2. Coding

const header = document.querySelector("#header");
const headerHeight = header.getBoundingClientRect().height;
 
window.addEventListener("scroll", () => {
      if (window.scrollY > headerHeight) {
      header.setAttribute("style", "background: white;");
   } else {
      
header.setAttribute("style", "background: transparent;");
   }
});

3. 설명

  1. 해당 DOM의 높이를 변수로 잡는다. – getBoundingClientRect().height;
  2. window에 scroll 이벤트를 더한 후, window의 scroll 위치가 DOM의 높이를 넘어설 경우- window.scrollY
  3. 해당 요소의 스타일 속성을 변경시킨다. element.setAttribute(“style”, “background: changestyle;”);
  4. 3번은 스타일을 직접 변경하는 방법 외에 classlist를 이용해 변경 할 수도 있다.

이 포스팅은 독학으로 배우고 정리하는거라 정석은 아닙니다.

혹시 더 효율적인 방법이 있다면 댓글로 알려주시면 감사하겠습니다!:)

Leave a comment

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다