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

자바스크립트 javascript 5스크롤이벤트window --> scroll

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

/// 스크롤이벤트

window --> scroll

window.addEventListener('scroll',function() {

실행코드;

});

 
    <style>

        * {
            margin:0;
            padding:0;
            box-sizing: border-box;
        }
        header {
            width: 100%;
            height: 150px;
            background-color: rgba(0,0,0,.5);
            font-size: 70px;
            text-align: center;
            position: fixed;
            left:0; top:0;
        }
        header.active {
            background-color: #f00;
        }

        main {
            width: 1000px;
            height: 3000px;
            background-color: #fc0;
            font-size: 300px;
            text-align: center;
            margin: 0 auto;
        }

        header.active {
            background-color: #f00;
        }

    </style>
</head>
<body>
    <header>Header</header>
    <main>Main</main>

    <script>

        const header = document.querySelector('header');

        window.addEventListener('scroll',function(){
            console.log('스크롤중입니다');
            // 스크롤바의 위치값
            // 스크롤을 하지 않았을때 스크롤바 위치값은 0부터시작
            // 스크롤바의 위치값이 특정값보다 클때 --> if문
            // header의 배경색을 바꾸기 --> 클래스로 제저

            // 현재 창의 스크롤바 위치값 가져오기
            // window.pageYOffset
            console.log(window.pageYOffset);


            if ( window.pageYOffset > 1 ) {
                // 스크롤바의 위치값이 1보다 클때
                header.classList.add('active')
            } else {
                // 스크롤바의 위치값이 1보다 작을때
                header.classList.remove('active');
            }
        });

    </script>
</body>
 
LIST

댓글