JS DOM_Style.Toggle

tpids·2024년 6월 13일

JS

목록 보기
40/40

class 속성 다루기 - 토글

document.요소명.classList.toggle()

  • HTML 요소의 class 속성값 존재확인 후 추가 또는 삭제

버튼을 눌렀을 때 다크모드로 바뀌는 기능을 구현

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .dark {
            background-color: black;
            color: white;
        }

        .light {
            background-color: white;
            color: black;
        }
    </style>
</head>
<body>
    <div id="container" class="light">
        <h1>안녕하세요. 반갑습니다</h1>
        <button id="btnText" onclick="changeMode()">dark 모드</button>
    </div>

    <script>
        // 1. changeMode 라는 이름의 함수를 선언
        const changeMode = () => {
            const container = document.getElementById('container');
            container.classList.toggle('dark');
            container.classList.toggle('light');

            const btnText = document.getElementById('btnText');
            if (container.classList.contains('dark')) {
                btnText.textContent  = 'Light 모드';
            } else {
                btnText.textContent = 'Dark 모드';
            }
        }
        // 2. dark모드 라는 버튼 클릭 시, 안에 있는 내용을 light 모드로 변경
        // light모드 버튼 클릭 시, 안에 있는 내용을 dark 모드로 변경
        // 버튼 태그에 접근 -> id 값 활용 -> 그안에 있는 글자를 변경
        // 현재 버튼에 어떤 모드가 적용이 돼 있는지 확인 필요 -> contains
        // toggle 기능을 사용!
        // class가 light => 버튼 클릭시 => class가 dark 디자인 변경
    </script>
</body>
</html>

업로드중..

profile
개발자

0개의 댓글