해결된 질문
작성
·
184
0
scrollLoop 함수에서 prevScrollHeight 부분의 값을 offsetTop으로 지정해도 될 것 같아서 테스트 해보았는데요. 0번섹션에서 1번 섹션으로 넘어가는 순간 if문이 반복되면서 currentScene이 1이 아니라 2가 되는 것 같더라구요.. 왜 offsetTop으로 하면 안되는 걸까요? ㅜㅜ
(() => {
let yOffset = 0; // window.pageYOffset
let prevScrollHeight = 0; // yOffset보다 이전에 위치한 섹션 높이 합
let currentScene = 0; // 현재 활성화된 scene
const sceneInfo = [
{
type: 'sticky',
heightNum: 5, // 브라우저 높이의 5배로 scrollHiehgt setting
scrollHeight: 0,
objs: {
container: document.querySelector('#scroll-section-0'),
},
},
{
type: 'normal',
heightNum: 5,
scrollHeight: 0,
objs: {
container: document.querySelector('#scroll-section-1'),
},
},
{
type: 'sticky',
heightNum: 5,
scrollHeight: 0,
objs: {
container: document.querySelector('#scroll-section-2'),
},
},
{
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() {
for (let i = 0; i < currentScene; i++) {
prevScrollHeight = sceneInfo[i].objs.container.offsetTop;
}
if(yOffset > prevScrollHeight + sceneInfo[currentScene].scrollHeight) {
currentScene++
}
if(yOffset < prevScrollHeight) {
currentScene--
}
console.log(currentScene);
}
window.addEventListener('resize', setLayout);
window.addEventListener('scroll', () => {
yOffset = window.pageYOffset;
scrollLoop();
});
setLayout();
})();
답변 2
0
0
offsetTop은 부모 엘리먼트의 위치를 기준으로 한 자식 엘리먼트의 위치이기 때문에 값에 차이가 있습니다.
0에서 1로 넘어갈 때를 생각해보면
각 씬의 scrollHeight를 더하는 방식은 0번의 높이를 반영하지만
0번의 offsetTop은 0이기 때문에 거기서부터도 차이가 발생합니다.
잘 이용하면 말씀대로 offsetTop으로도 구현할 수는 있겠지만, 조건에 따라 대응하기가 더 복잡하다고 생각이 됩니다^^