⊹⠀𝚓𝚚𝚞𝚎𝚛𝚢

❏ JQuery - 스크롤 시 나타나는 요소만들기!(Fade In)

김_코드 2023. 6. 27. 16:28

 

 

안녕하세요!

 

오늘은 페이지 구현 시 제이쿼리를 사용하여,

 

페이지를 스크롤할 때마다 숨겨진 요소가 나타나게 하는 효과에 대해서 알아보겠습니다!


먼저 html로 간단한 구조를 만듭니다.

 

✎html

<section>
    <div id="container1">1</div>
    <div id="container2">2</div>
    <div id="container3">3</div>
    <div id="container4">4</div>
    <div id="container5">5</div>
</section>

✎css

section div{
    width: 100%;
    height: 100vh;
}

section #container1{
    background: orange;
}

section #container2{
    background: green;
}

section #container3{
    background: salmon;
}

section #container4{
    background: black;
}

section #container5{
    background: greenyellow;
}

하나의 섹션 안에 continer라는 ID 값을 가진 div들이 존재합니다.

그러고 각각의 continer들은 색으로 영역을 표현합니다.( 여러분들이 원하는 색으로도 변경이 가능합니다!)

 

그러면 이러한 화면이 나타나게 됩니다.

 

 


여기에서 html의 코드에서 각각의 컨테이너 박스에 class명을 줍니다.

클래스 명으로는 hideme로 작성해 줍니다!

    <section>
        <div id="container1" class="hideme">1</div>
        <div id="container2" class="hideme">2</div>
        <div id="container3" class="hideme">3</div>
        <div id="container4" class="hideme">4</div>
        <div id="container5" class="hideme">5</div>
    </section>

 

또한 css로 한가지 더 추가해 주세요!

.hideme{
    opacity: 0;
}

 

이제는 제이쿼리를 사용해서 코드를 작성해 봅시다.

html 상단 <head>에 제이쿼리를 추가해 주세요!

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

✎JQuery

        $(document).ready(function() {
            $(window).scroll( function(){
                $('.hideme').each( function(i){
                    var bottom_of_object = $(this).offset().top + $(this).outerHeight();
                    var bottom_of_window = $(window).scrollTop() + $(window).height();
                    if( bottom_of_window > (bottom_of_object * 0.7) ){
                        $(this).animate({'opacity':'1'},1500);
                    }
                }); 
            });
        });
        
// window.scrolltop -> 최상단에서 스크롤한 정도
// window.height -> 현재 창 높이 값

 

그럼 구현된 화면을 볼까요??

 

처음엔 빈화면으로 보이지만 스크롤을 내리면 투명도가 조절되어 화면에 나타나게 되는 것을 볼 수 있었습니다!

 


o(^▽^) o