jineecode

스크롤시 해당 섹션의 메뉴를 활성화 시키기(jquery편) 본문

JS/jquery

스크롤시 해당 섹션의 메뉴를 활성화 시키기(jquery편)

지니코딩 2020. 12. 11. 12:44

  $(window).scroll(function(){
    let scroll = $(window).scrollTop();
  
  // offSet().top이 4개 필요하므로 반복문 사용
  for(let i = 0; i < $("article").length; i++) {
    // console.log(i+"안녕<br>");

    // article 각각의 높이를 읽어준다.
    let articleTop = $("article").eq(i).offset().top;
    // console.log(articleTop)
    
    // articleTop + article의 높이 = articlebottom
    let articleBottom = articleTop + $("article").eq(i).outerHeight();
    let winHeight = $(window).height();
    let scrollBottom = $(".wrap").height() - winHeight - 50;

    // scroll이 article보다 크거나 작고, articlebottom보다 작으면 해당 article의 영역이 됨
    if(scroll >= articleTop -51 && scroll < articleBottom) {
      $(".gnb li").removeClass("active");
      $(".gnb li").eq(i).addClass("active");
    } 

    if(scroll >= scrollBottom) {
      $(".gnb li").eq(2).removeClass("active");
      $(".gnb li").eq(3).addClass("active");
    }
  }

1.

전역객체인 window의 scroll의 기준을 잡는다.

window의 현재 scrollTop 위치를 잡기 위해 변수명 scroll에 담는다.

 

2.

패널의 top이 총 4개 필요하므로 반복문을 사용한다.

for(let i = 0; i < $("article").length; i++){}

 

3.

article 각각(배열 사용)의 높이를 읽는다. 변수 articleTop에 담음.

let articleTop = $("article").eq(i).offset().top;

 

4.

article bottom의 위치는 articleTop의 위치에 article의 높이를 더하면 나온다.

let articleBottom = articleTop + $("article").eq(i).outerHeight();

 

5.

scroll이 article보다 크거나 작고, articlebottom보다 작으면 해당 article의 영역이 된다.

".gnb li" 에 "active class"를 모두 없애고

해당 배열 ".gnb li"에 "active"를 넣어준다.

if(scroll >= articleTop -51 && scroll < articleBottom) {
      $(".gnb li").removeClass("active");
      $(".gnb li").eq(i).addClass("active");
    } 

 

6.

마지막 contact me는 "My work" 구역과 겹치므로 따로 위치를 강제한다.

컨텐츠의 모든 높이를 구해서 window 높이를 빼면 된다.

 

let winHeight = $(window).height();
let scrollBottom = $(".wrap").height() - winHeight - 50;

 

scroll이 scrollBottom보다 크거나 같으면

My work(eq(2))의 active를 없애고

Contact me(eq(3))의 active를 넣어준다.

 if(scroll >= scrollBottom) {
      $(".gnb li").eq(2).removeClass("active");
      $(".gnb li").eq(3).addClass("active");
    }

'JS > jquery' 카테고리의 다른 글

animate  (0) 2020.12.14
event  (0) 2020.12.14
attr method  (0) 2020.12.14
요소의 위치 .offset() .position()  (0) 2020.12.11
display를 변경시키는 메서드  (0) 2020.12.03
Comments