본문 바로가기

프로젝트/애플 웹사이트 클론

[ 애플 웹사이트 클론 ] 현재 스크롤 섹션에 따른 아이디값 부여

현재 스크롤섹션의 아이디값에 따라 다른 태그들을 보여주기 위해서, 아이디값을 부여해보자.

 

 

 

 

아래와 같이 CSS가 적용이 되어있다.

.sticky-elem {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}

#show-scene-0 #scroll-section-0 .sticky-elem,
#show-scene-1 #scroll-section-1 .sticky-elem,
#show-scene-2 #scroll-section-2 .sticky-elem,
#show-scene-3 #scroll-section-3 .sticky-elem {
  display: block;
}

 

기존의 sticky-elem이라는 class는 display:none;이기 때문에 보이지 않는다.

그러다가 #show-scene-0 #scroll-section-0 아이디 값에 속하게 되면 display:block; 으로 바뀌면서 보이게 되는 방식이다.

 

 

 

 

 

 

document.body.setAttribute 를 사용하여, 요소의 속성값을 지정해줄 수 있다.

    document.body.setAttribute("id", `show-scene-${currentScene}`);

 

 

 

 

 

 

각 함수가 실행될 때마다, body값에 아이디값을 지정해주면 스크롤을 내릴 때마다 다른 메세지들을 볼 수 있다.

  function setLayout() {
    //각 스크롤 섹션의 높이 세팅
    for (let i = 0; i < sceneInfo.length; i++) {
      sceneInfo[i].scrollHeight = sceneInfo[i].hieghtNum * window.innerHeight;
      sceneInfo[
        i
      ].objs.container.style.height = `${sceneInfo[i].scrollHeight}px`;
    }
    let totalScrollHeight = 0;
    yOffset = window.pageYOffset;

    for (let i = 0; i < sceneInfo.length; i++) {
      totalScrollHeight += sceneInfo[i].scrollHeight;
      if (totalScrollHeight >= yOffset) {
        currentScene = i;
        break;
      }
    }
    document.body.setAttribute("id", `show-scene-${currentScene}`);
  }

  function scrollLoop() {
    prevScrollHeight = 0;
    for (let i = 0; i < currentScene; i++) {
      prevScrollHeight += sceneInfo[i].scrollHeight;
    }
    if (yOffset > prevScrollHeight + sceneInfo[currentScene].scrollHeight) {
      currentScene++;
      document.body.setAttribute("id", `show-scene-${currentScene}`);
    }
    if (yOffset < prevScrollHeight) {
      currentScene--;
      document.body.setAttribute("id", `show-scene-${currentScene}`);
    }
    console.log(currentScene);
  }

  window.addEventListener("scroll", () => {
    yOffset = window.pageYOffset;
    scrollLoop();
  });
  window.addEventListener("resize", setLayout);
  window.addEventListener("load", setLayout);

 

 

 

 

 


 

다음 스크롤 섹션을 넘어가자마자, 새로운 아이디값이 부여되고 새로운 텍스트가 보인다.