[jQuery]모달창(madal)

김나나·2024년 1월 19일
0

jQuery

목록 보기
17/19

body

    <div class="con_wrap">
        <div class="con con_1">컨텐츠1</div>
        <div class="con con_2">컨텐츠2</div>
        <div class="con con_3">컨텐츠3</div>
    </div>

    <div class="modal_wrap modal_wrap_1">
        <div class="modal modal_1">
            <h3>모달 내용1</h3>
            <div class="close">X</div>
        </div>
    </div>
    <div class="modal_wrap modal_wrap_2">
        <div class="modal modal_2">
            <h3>모달 내용2</h3>
            <div class="close">X</div>
        </div>
    </div>
    <div class="modal_wrap modal_wrap_3">
        <div class="modal modal_3">
            <h3>모달 내용3</h3>
            <div class="close">X</div>
        </div>
    </div>

style

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

        .con_wrap{
            display: flex;
            justify-content: space-around;
            margin: 100px auto;
        }

        .con{
            width: 300px;
            height: 400px;
            background-color: salmon;
            cursor: pointer;
        }

        .modal_wrap{
            width: 100%;
            height: 100vh;
            background-color: rgba(0, 0, 0, 0.4);
            position: fixed;
            top: 0;
            left: 0;
            display: none;
        }

        .modal{
            width: 400px;
            height: 450px;
            background-color: #fff;
            display: flex;
            justify-content: space-between;
            padding: 30px;
            box-sizing: border-box;
            border-radius: 20px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        .close{
            font-weight: 900;
            cursor: pointer;
        }

script

        $(document).ready(function(){

            $('.con').each(function(i){
                $(this).attr({
                    "data-index": i
                });
            }).click(function(){
                var choice = $(this).attr('data-index');
                $('.modal_wrap').eq(choice).fadeIn(500);
            });

            $('.close, .modal_wrap').click(function(){
                $('.modal_wrap').fadeOut(500);
            });

        });

=> each와 attr을 사용하여 con에 data-index로 순서를 부여.
클릭한 con의 숫자를 choice변수로 받아와서 modal_wrap을 eq선택자로 5초를 두고 fadeIn을 해줌.
처음에는 close버튼을 눌렀을 때에만 fadeOut을 5초 간격으로 두고 해주려 했으나,
작은 x버튼을 클릭하는 것이 더 힘들다고 판단하여 modal_wrap을 다시 한 번 눌러줬을 때에도
fadeOut이 적용되도록 하였음.

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

0개의 댓글