Image Gallery

Namiya·2025년 7월 14일

JavaScript 연습

목록 보기
23/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>Image gallery</title>
    <style>

        #container {
            width: 960px;
            margin: 0 auto;
        }

        #main {
            display: block;
            width: 100%;
            margin-bottom: 10px;
        }

        #gallery {
            display: flex;
            justify-content: center;
            gap: 10px;
        }

        #gallery > li > img{
            display: block;
            width: 200px;

            /* 사용자의 편의를 위해 마우스 포인터의 모양을 손가락으로 설정 */
            cursor: pointer;
        }

    </style>
</head>
<body>

    <div id="container">
        <img id="main" src="https://i.imgur.com/7Mu8BZg.png" alt="main-image">

        <ul id="gallery">
            <li><img src="https://i.imgur.com/7Mu8BZg.png" alt="gallery-image"></li>
            <li><img src="https://i.imgur.com/kwD72gU.png" alt="gallery-image"></li>
            <li><img src="https://i.imgur.com/qOU9yuQ.png" alt="gallery-image"></li>
        </ul>
    </div>

    <script>

        // 프로그램에서 참조하는 요소를 미리 탐색
        const main = document.querySelector("#main");
        const gallery = document.querySelectorAll("#gallery > li > img");

        // 1. 썸네일 이미지를 클릭하면
        for (let i = 0; i < gallery.length; i++) {
            gallery[i].addEventListener("click", function (event) {
                // 이벤트 핸들러: <img> 요소에 click 이벤트가 발생하면 실행할 기능

                // 2. #main 요소의 이미지를 클릭한 썸네일 이미지로 바꾼다.
                // #main.setAttribute('src', this.getAttribute('src'));
                main.src = this.src;
            });
        }

    </script>

</body>
</html>

0개의 댓글