Standard Event Model Toggle

Namiya·2025년 7월 11일

JavaScript 연습

목록 보기
21/27
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta name="viewport" content="width=device-width">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://meyerweb.com/eric/tools/css/reset/reset.css">
    <title>Toggle</title>
    <style>

        #step {
            margin-bottom: 50px;

            font-size: 3em;
            font-weight: bolder;
        }

        #toggle {
            width: 90px;
            height: 30px;
        }

    </style>
</head>
<body>

    <h1 id="step">Step by stop goes a long way.</h1>

    <p>
        <button type="button" id="toggle">TOGGLE</button>
    </p>

    <script>

        // 프로그램에서 참조하는 요소를 미리 탐색
        const string = document.getElementById('step');
       
        // 1. #toggle 요소를 클릭하면
        // → #toggle 요소를 표현하는 HTMLElement 객체에 click 이벤트 핸들러를 연결
        document.getElementById('toggle').addEventListener('click', function () {
            // 이벤트 핸들러: #toggle 요소에 click 이벤트가 발생하면 실행할 기능

            // 2. #step 요소의 글자 색상이 설정되어 있지 않으면, 즉 글자 색상이 "red"가 아니면,
            //    또는 #toggle 요소의 내부 텍스트가 "RESET"이 아니면, 즉 "TOGGLE"이면
            string.style.color = this.innerHTML === 'TOGGLE' ? 'red' : '';
            this.innerHTML = this.innerHTML === 'TOGGLE' ? 'RESET' : 'TOGGLE';
        });

    </script>

</body>
</html>

0개의 댓글