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

자바스크립트 javascript 12. (3) 애니메이션을 활용하여 스크롤에 위치했을때 생겨나는 애니메이션 코드

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

 

    <style>

        * {
            margin: 0;
            padding:0;
        }

        .box {
            height: 800px;
            padding-top: 150px;
        }
        .box:nth-child(odd ) {
            background-color: #ccc;
        }
        .box:nth-child(even) {
            background-color: #fc0;
        }
        .box h2 {
            text-align: center;
            font-size: 50px;
            text-transform: uppercase;
            transform: translateY(300%);
            opacity: 0;
            /* 
                uppercase : 대문자
                lowercase : 소문자
            */
        }

        .box h2.ani {
            animation-name: moveUp;
            animation-duration: 3s;
            animation-fill-mode: both;
            animation-timing-function: ease-in-out;
        }

        


        @keyframes moveUp {
            0% { transform: translateY(300%); opacity: 0;}
            100% { transform: translateY(0); opacity: 1;}
        }

    </style>
</head>
<body>
    <div class="box box1">
        <h2>title1</h2>
    </div>
    <div class="box box2">
        <h2>title2</h2>
    </div>
    <div class="box box3">
        <h2>title3</h2>
    </div>
    <div class="box box4">
        <h2>title4</h2>
    </div>
    <div class="box box5">
        <h2>title5</h2>
    </div>

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

        $('.box1 h2').addClass('ani');

        // 스크롤 이벤트
        $(window).on('scroll', function() {

            // 현재스크롤바의 위치값 가져오기
            let s_yPos = $(window).scrollTop();
            // 현재창의 높이값 가져오기
            let w_height = $(window).height();
            // 박스2의 titie요소 offset top 가져오기
            let t_top = $('.box2 h2').offset().top;

            

            // if문을 이용하여 타이틀 요소가 화면에 들어오는 시점 찾아내기
            if ( w_height + s_yPos > t_top ) {
                $('.box2 h2').addClass('ani');
            } else {
                $('.box2 h2').removeClass('ani');
            }
        });

    </script>
 

 

 

LIST

댓글