[javaScript]스크롤 이벤트 헤더 게이지

김나나·2024년 2월 1일

javaScript

목록 보기
15/25


=> 스크롤을 내릴수록 상단에 게이지가 붉은 색으로 차오르는 것을 볼 수 있음

body

    <div class="wrap">

        <header>

            <div class="progress">
                <div class="gage"></div>
            </div>

        </header>

        <section class="section_1">
            <h3>첫 번째 섹션</h3>
        </section>

        <section class="section_2">
            <div class="con"></div>
            <div class="con"></div>
            <div class="con"></div>
        </section>

        <section class="section_3">
            <h3>세 번재 섹션</h3>
        </section>

    </div>

style.css

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

header{
    width: 100%;
    height: 80px;
    background-color: gray;
    border-bottom: 1px solid #eee;
    position: fixed;
    top: 0;
    left: 0;
}

.progress{
    height: 10px;
    background-color: lightgray;
}

.gage{
    width: 0%;
    height: 100%;
    background-color: crimson;
}

section{
    font-size: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.section_1{
    height: 80vh;
    background-color: lightgray;
}

.section_2{
    padding: 200px 20%;
    display: flex;
    justify-content: space-between;
}

.con{
    width: 30%;
    height: 450px;
    background-color: lightgray;
}

.section_3{
    height: 500px;
    background-color: lightgray;
}

=> 게이지는 width의 %가 높을 수록 게이지가 차는 느낌을 보여줄 수 있음(해당 코드에서는 .gage의 width값)

main.js

(function(){

    const wrapEl = document.querySelector('.wrap');
    const gageEl = document.querySelector('.gage');

    const scrollHandler = () => {
        const pageY = pageYOffset;
        
        const useScroll = wrapEl.offsetHeight - window.innerHeight;
        
        const perResult = (pageY / useScroll) * 100;
        
        gageEl.style.width = `${perResult}%`;
    }

    window.addEventListener('scroll', scrollHandler);

})();

=> 스크롤을 내리면 게이지 바가 올라가게 만들어야 함.

실제 사용 가능 높이값 = 전체 - 스크롤바의 높이

=> 전체 높이값을 offsetHeight로 구해옴
=> innerHeight로 스크롤바의 높이를 알 수 있음(브라우저 size와 동일 비율이기 때문)

퍼센트값 = 스크롤의 위치 / 실제 사용 가능 높이값 * 100

=> 위 코드의 const perResult = (pageY / useScroll) * 100 참고

profile
10분의 정리로 10시간을 아낄 수 있다는 마음으로 글을 작성하고 있습니다💕

0개의 댓글