본문 바로가기
Front-end/jQuery

[jQuery, script] 스크롤 이동

by Gi-One 2023. 2. 10.

#스크롤이동 #scrollto #animation #script #jquery

 

 

안녕하세요. Gi-1의 개발일기입니다.

퍼블리싱을 하다보면 컨텐츠 영역으로 바로 이동하게끔 ~~url/#이동할컨텐츠영역id를 이용하는 경우가 많은데요,

css로 스크롤 애니메이션 을 줄 수도 있지만 저는 script가 편하더라구요!

 

 

 

 

css로 이용할 경우

html{

 scroll-behavior:smooth;

}

 

 

script

      function moveScroll(){
        var ingSec = document.querySelector("#id");
        var ingLocation = ingSec.offsetTop;

        if(ingLocation == $(document).scrollTop()){
          return false;
        }
        // 이미 스크롤 위치에 있을 경우 작동 X
        $('html, body').animate({scrollTop: ingLocation}, 1000);
      }

 

 

 

다만, 메뉴의 헤더가 fixed된 경우에 컨텐츠 영역을 헤더가 가릴 수 있습니다.

그래서 저는 아래와 같이 작성하였습니다.


      function moveScroll(){
        var ingSec = document.querySelector("#id");
        var ingLocation = ingSec.offsetTop;
        var windowWidth = $( window ).width();

        if(windowWidth > 960) {
            var scrollLocation = ingLocation - 70 ;
        } else {
            var scrollLocation = ingLocation - 30 ;
        }
        // 메뉴 크기에 따른 스크롤 미세조정

        if(scrollLocation == $(document).scrollTop()){
          return false;
        }
        // 이미 스크롤 위치에 있을 경우 작동 X
        $('html, body').animate({scrollTop: scrollLocation}, 1000);
      }
 

페이지의 길이가 너무 길 경우, 페이지 내 로딩속도 떄문에 setTimeout을 걸어줘야 하는 경우도 있는 것 같습니다.

댓글