Script Sample/Parallax Effect
Parallax Effect 01 - 메뉴 이동
Gentlemanjs
2022. 3. 7. 18:16
document.querySelectorAll("#parallax__nav li a").forEach(li =>{ // 메뉴 탭
li.addEventListener("click", e => {
e.preventDefault(); // 작동 금지
document.querySelector(li.getAttribute("href")).scrollIntoView({ // li의 속성값들을 가져와서 스크롤 됐을때
behavior:"smooth" // 부드럽게
})
})
})
window.addEventListener("scroll", ()=>{ // 스크롤 했을 때
let scrollTop = window.pageYOffset || document.documentElement.scrollTop || window.scrollY; // 스크롤값을 변수로 설정
document.querySelectorAll(".content__item").forEach((el, index) => { // 이미지들
if( scrollTop >= el.offsetTop - 2){ // 스크롤값과 이미지의 Top값과 같을 때
document.querySelectorAll("#parallax__nav li").forEach(li => { // 메뉴들에게
li.classList.remove("active"); // active 지우고
});
document.querySelector("#parallax__nav li:nth-child("+(index+1)+")").classList.add("active") // 해당하는 메뉴에 active 활성화
}
})
// info
document.querySelector(".scrollTop span").innerText = Math.round(scrollTop); // 좌표값들 입력
document.querySelector(".offset1").innerText = document.getElementById("section1").offsetTop
document.querySelector(".offset2").innerText = document.getElementById("section2").offsetTop
document.querySelector(".offset3").innerText = document.getElementById("section3").offsetTop
document.querySelector(".offset4").innerText = document.getElementById("section4").offsetTop
document.querySelector(".offset5").innerText = document.getElementById("section5").offsetTop
document.querySelector(".offset6").innerText = document.getElementById("section6").offsetTop
document.querySelector(".offset7").innerText = document.getElementById("section7").offsetTop
document.querySelector(".offset8").innerText = document.getElementById("section8").offsetTop
document.querySelector(".offset9").innerText = document.getElementById("section9").offsetTop
})
전체 스크롤값과 이미지위치값을 비교해서 Parallax Effect 를 주는 예제입니다.
let scrollTop = window.pageYOffset;
let scrollTop = document.documentElement.scrollTop
let scrollTop = window.scrollY;
위와 같은 명령어로 스크롤값을 추출할 수 있습니다.
또한 이미지에 .offsetTop 을 이용하여 Y축 좌표값을 추출하고
스크롤값과 비교하는 방식을 사용했습니다.