• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    해결됨

scrollHeight 오류

20.09.17 22:25 작성 조회수 618

0

디버깅 했을 때는 값이 잘 들어간게   

확인되었는데 실행하면 콘솔에 Cannot read property 'scrollHeight' of undefined

에러가 발생하네요 ㅠㅠㅠ 뭐가 문제일까요?

currentScene을 console.log 해보니 -1이 나오네요..


(() => {
  let yOffset = 0; // window.pageYOffset 대신 쓸 변수
  let prevScrollHeight = 0; //현재 스크롤 위치(yOffset)보다 이전에 위치한 스크롤 섹션들의 스크롤 높이값의 합
  let currentScene = 0; //현재 활성화된(눈 앞에 보고 있는) 씬(scroll-section)

  const sceneInfo = [
    {
      //0
      type: "sticky",
      heightNum: 5, //브라우저 높이의 5배로 scrollHeight 세팅
      scrollHeight: 0,
      objs: {
        container: document.querySelector("#scroll-section-0"),
      },
    },
    {
      //1
      type: "normal",
      heightNum: 5,
      scrollHeight: 0,
      objs: {
        container: document.querySelector("#scroll-section-1"),
      },
    },
    {
      //2
      type: "sticky",
      heightNum: 5,
      scrollHeight: 0,
      objs: {
        container: document.querySelector("#scroll-section-2"),
      },
    },
    {
      //3
      type: "sticky",
      heightNum: 5,
      scrollHeight: 0,
      objs: {
        container: document.querySelector("#scroll-section-3"),
      },
    },
  ];

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

  function scrollLoop() {
    prevScrollHeight = 0;
    for (let i = 0; i < sceneInfo.length; i++) {
      prevScrollHeight += sceneInfo[i].scrollHeight;
    }
    if (yOffset > prevScrollHeight + sceneInfo[currentScene].scrollHeight) {
      currentScene++;
    }
    if (yOffset < prevScrollHeight) {
      //if (currentScene === 0) return; //브라우저 바운스 효과로 인해 마이너스가 되는 것을 방지(모바일)
      currentScene--;
    }
    document.body.setAttribute("id", `show-scene-${currentScene}`);
    console.log(currentScene);
  }

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

답변 1

답변을 작성해보세요.

1

scrollLoop 함수에서 for문의 조건이 잘못 들어갔습니다^^
sceneInfo.length를 currentScene으로 바꾸어주세요~

수정 전

function scrollLoop() {
	  prevScrollHeight = 0;
	  for (let i = 0; i < sceneInfo.length; i++) {
		prevScrollHeight += sceneInfo[i].scrollHeight;
	  }

수정 후

function scrollLoop() {
	  prevScrollHeight = 0;
	  for (let i = 0; i < currentScene; i++) {
		prevScrollHeight += sceneInfo[i].scrollHeight;
	  }