티스토리 뷰

 

설명

현재 스크롤값에 따라서 섹션을 이동할때 섹션에 맞는 메뉴에 표시가 됩니다.

먼저 각 섹션별 offsetTop값을 구하고 현재 스크롤값이 각 섹션별 offsetTop값보다 같거나 커질 경우 메뉴에 표시가 됩니다.

document.querySelectorAll("#parallax__nav li a").forEach(li => {
    li.addEventListener("click", (e) => {
        e.preventDefault();
        document.querySelector(li.getAttribute("href")).scrollIntoView({
            behavior:"smooth"
        })
    })
})

window.addEventListener("scroll", () => {
    let scrollTop = window.pageYOffset || document.documentElement.scrollTop || window.scrollY;

    //forEach()문
    document.querySelectorAll(".content__item").forEach((el, index) => {
        if(scrollTop >= el.offsetTop -2){
            document.querySelectorAll("#parallax__nav ul li").forEach(li => {
            li.classList.remove("active")
            })
            document.querySelector("#parallax__nav ul li:nth-child("+(index+1)+")").classList.add("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
})
댓글
© 2018 webstoryboy