Notice
Recent Posts
Recent Comments
Link
«   2026/06   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Archives
Today
Total
관리 메뉴

학습기록남기기

2022_05_30_JS_6일 본문

수업_정리

2022_05_30_JS_6일

backend_na 2022. 5. 31. 09:41
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
        .toggle li {
            display: inline-block;
            padding: 15px 20px 14px;
            width: 25%;
            text-align: center;
            border: 1px solid #333;
            cursor: pointer;
        }
        .toggle-menu {
            display: none;
        }
        .active {
            display: block;
            animation: fadeIn 0.5s ease-in-out;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            } to {
                  opacity: 1;
              }
        }
    </style>
</head>
<body>

<ul class="toggle">
    <li data-id="#toggle1">메뉴1</li>
    <li data-id="#toggle2">메뉴2</li>
    <li data-id="#toggle3">메뉴3</li>
</ul>

<div>
    <div class="toggle-menu active" id="toggle1">
        토글메뉴 1
    </div>
    <div class="toggle-menu" id="toggle2">
        토글메뉴 2
    </div>
    <div class="toggle-menu" id="toggle3">
        토글메뉴 3
    </div>
</div>

<script>
    /*
    1. ul에 이벤트 전파 이용해서 클릭이벤트를 걸고
     클릭되는 타겟의 data-id를 얻습니다.
    2. toggle-menu의 active속성을 삭제
    3. data-id 값에 알맞는 태그에 active속성 추가.
    */

    const $toggle = document.querySelector('.toggle');
    $toggle.onclick = function(e) {
        if(!e.target.matches('.toggle > li')) {
            return;
        }

        const $toggleList = document.querySelectorAll('.toggle-menu');
        for(let $ele of $toggleList) {
            // $ele.classList.toggle('active', '#' + $ele.id === e.target.dataset.id);
            $ele.classList.toggle('active', document.querySelector(e.target.dataset.id) === $ele);
        }

        /*
        for(let i=0; i<$toggleList.length; i++) {
            if($toggleList[i].classList.contains('active')) {
                $toggleList[i].classList.remove('active');
            }
        }

        const target = e.target.dataset.id;
        document.querySelector(target).classList.add('active');
        */
    }

</script>

</body>
</html>

'수업_정리' 카테고리의 다른 글

2022_06_02_Spring_1일  (0) 2022.06.02
2022_05_31_JS_7일  (0) 2022.05.31
2022_05_27_JS_5일  (0) 2022.05.27
2022_05_26_JS_4일  (0) 2022.05.26
2022_05_25_JS_3일  (0) 2022.05.25