코드노트

스크롤 상단 고정 네비게이션 본문

Code note/자바스크립트

스크롤 상단 고정 네비게이션

코드노트 2022. 12. 31. 02:51
function scroll() {
  const header = document.querySelector("header"); // 
  const maxheight = header.clientHeight; // 

  document.addEventListener("scroll", onScroll, { passive: true });
  
  function onScroll() {
    const scrollLocation = document.documentElement.scrollTop;
    const bar = document.querySelector(".scroll_search");
    if (maxheight <= scrollLocation) {
      bar.classList.add("fix");
      bar.style.display = "block";
    } else {
      bar.style.display = "none";
      bar.classList.remove("fix");
    }
  }
}
scroll();

clientHeight : 요소의 내부 높이 ( 패딩값 포함 /스크롤바, 테두리 마진 제외)

- offsetHeight : 요소 내부 높이 ( 패딩값, 스크롤바, 테두리(border) 포함 / 마진 제외)

- scrollHeight : 요소 컨텐츠의 전체 높이 ( 패딩값, 스크롤바 포함 / 마진 제외

 

passive: true : false일 경우에는 touchstart, touchmove 와 같은 이벤트가 발생할 때 preventDefault로 실제 이벤트 자체를 막을 수 있다. 브라우저는 scroll이 계속 진행되는지 매번 감시한다.

true일 경우에는 preventDefault를 이용하여 scroll이벤트를 막지 않겠다는 의미.

* chrome 54+부터는 기본값이 true 사용안해도됨

 

scrollTop : 현재 스크롤 위치, 브라우저 상단에서 현재 스크롤까지 이동한 값