본문 바로가기
프론트엔드 개발자/JS

자바스크립트 javascript 12. (2) 움직이면 고정되는 스크롤바 만들기

by 신디블로그 2023. 4. 13.
SMALL

 

 

    <style>

        * {
            margin: 0;
            padding:0;
        }

        .hh {
            width: 100%;
            position: absolute;
            left:0; top:0;
            z-index: 100;
        }
        .hh .top {
            height: 50px;
            background-color: #fc0;
            text-align: center;
            font-size: 30px;
        }
        .hh .bt {
            height: 120px;
            background: rgba(0,0,0,.2);
            font-size: 80px;
            color:#000;
            text-align: center;
        }
        .hh .bt.on {
            background-color: #fff;
        }
        .hh.active .bt {
            position: fixed; /* 뷰포트 기준 */
            left:0; top:0;
            width: 100%;
        }


        .mm {
            height: 2000px;
            background-image: linear-gradient(0deg, yellow, green);
            text-align: center;
            font-size: 300px;
            font-weight: bold;
            color:#fff;
        }

        .up {
            position: fixed;
            right:100px; bottom:100px;
            width: 100px;
            height: 100px;
            opacity: 0;
            transition: opacity 0.5s;
        }
        .up.active {
            opacity: 1;
        }

    </style>
</head>
<body>
    <header class="hh">
        <div class="top">Top</div>
        <div class="bt">Bottom</div>
    </header>
    <main class="mm">Main</main>
    <button class="up">위로가기</button>

    <!-- jquery loading -->
    <script src="jquery/jquery-3.6.4.min.js"></script>
    <script>       

        // 스크롤 이벤트 생성
        $(window).on('scroll', function() {
            // 스크롤시 스크롤바의 위치값 찾아내기
            let yPos = $(window).scrollTop();
            console.log(yPos);

            // 현재스크롤바의 위치값을 비교하여 헤더바텀 색상변경하기
            if ( yPos > 1 ) {
                $('.hh .bt').addClass('on');
            } else {
                $('.hh .bt').removeClass('on');
            }

            // 현재스크롤바의 위치값을 비교하여 헤더영역 고정시키기
            if ( yPos > 50 ) {
                $('.hh, .up').addClass('active');
            } else {
                $('.hh, .up').removeClass('active');
            }

        });


    </script>
 

 

 

LIST