Post

레이아웃 이미지 슬라이드 4 - javascript

레이아웃 슬라이드 이미지 만들기

slider4-1

slider4-2

이미지는 sliderWrap 안에 있습니다.

완성화면

오른쪽에 있는 총 3개의 이미지가 서서히 생기는 이미지 슬라이드 입니다.

jquery와 javascript 를 사용하여 이 애니메이션을 할 수 있습니다.
javascrip / jquery 를 따로따로 작성하여 한 줄씩 분석해보겠습니다!




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
        window.onload = function () {
            let currentIndex = 0;   //현재 이미지   
            const slider = document.querySelectorAll(".slider"); //각각의 이미지들
            slider.forEach(el => el.style.opacity = "0");   //모든 이미지 투명도 0
            slider[0].style.opacity = 1;    //첫번째 이미지는 투명도 1

            setInterval(() => {
                let nextIndex = (currentIndex + 1) % slider.length;

                slider[currentIndex].style.opacity = "0";
                slider[nextIndex].style.opacity = "1";
                slider.forEach(el => el.style.transition = "all 1s");

                currentIndex = nextIndex;
            }, 3000);
        }


간단한 이미지 슬라이더의 기능을 수행하는 javascript 코드입니다.


바로 코드를 분석해보겠습니다.


1
window.onload = function () {
  • 이 코드는 window.onload 이벤트를 사용하여 페이지의 모든 콘텐츠(이미지, 스타일시트, 스크립트 등)가 완전히 로드된 후에 함수를 실행하도록 설정합니다.
    이는 모든 리소스가 준비된 후에 스크립트가 실행되어야 할 때 유용합니다.


1
    let currentIndex = 0;   //현재 이미지
  • let currentIndex = 0;: 현재 표시되고 있는 이미지의 인덱스를 0으로 설정합니다. 이는 첫 번째 이미지부터 슬라이드를 시작한다는 것을 의미합니다.


1
    const slider = document.querySelectorAll(".slider"); //각각의 이미지들
  • .slider 클래스를 가진 모든 요소를 선택하여 slider 상수에 할당합니다.
    이는 슬라이드 쇼에서 관리해야 하는 모든 슬라이더 요소를 나타냅니다.


1
    slider.forEach(el => el.style.opacity = "0");   //모든 이미지 투명도 0
  • forEach 메서드를 사용하여 slider NodeList의 각 요소(이미지)에 대해 실행됩니다.
    각 슬라이더의 투명도(opacity)를 0으로 설정하여 처음에 보이지 않도록 합니다.


1
    slider[0].style.opacity = 1;    //첫번째 이미지는 투명도 1
  • 첫 번째 슬라이더 요소의 투명도를 1로 설정하여 페이지 로드 시 첫 번째 이미지만 보이도록 합니다.


1
    setInterval(() => {
  • setInterval 함수를 사용하여 주어진 함수를 반복적으로, 여기서는 3000밀리초(3초)마다 실행합니다.
    이 함수 내에서 슬라이드 전환 로직이 실행됩니다.


1
        let nextIndex = (currentIndex + 1) % slider.length;
  • 다음 슬라이드로 전환하기 위해 nextIndex를 계산합니다.
    currentIndex + 1을 slider.length로 나눈 나머지를 사용하여 순환적인 슬라이드 쇼를 만듭니다.


1
2
3
        slider[currentIndex].style.opacity = "0";
        slider[nextIndex].style.opacity = "1";
        slider.forEach(el => el.style.transition = "all 1s");
  • 현재 슬라이더의 투명도를 0으로 설정하고, 다음 슬라이더의 투명도를 1로 설정하여 슬라이드가 보이도록 합니다.
    모든 슬라이더에 대해 transition 속성을 all 1s로 설정하여 투명도 변경이 1초 동안 부드럽게 전환되도록 합니다.


1
        currentIndex = nextIndex;
  • currentIndex를 nextIndex로 업데이트하여 다음 반복에서 현재 슬라이더로 사용될 수 있도록 합니다.


1
2
    }, 3000);
});
  • setInterval의 반복 주기를 닫고 window.onload 함수 블록의 끝을 나타냅니다.
    여기서 3000은 각 슬라이드 전환 사이의 시간 간격을 밀리초 단위로 지정합니다.


전체 코드

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
<!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>웹디자인기능사 슬라이드 S-4</title>
    <link href="https://webfontworld.github.io/gmarket/GmarketSans.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            font-family: 'GmarketSans';
        }

        #wrap {
            width: 100%;
        }

        #main {
            width: 100%;
            height: calc(100vh - 120px);
            background-color: #e4adff;
            display: flex;
        }

        #header {
            width: 200px;
            height: 100%;
        }

        #header h1 {
            width: 100%;
            height: 10%;
            background-color: #d59be1;
        }

        #header nav {
            width: 100%;
            height: 90%;
            background-color: #ff74f3;
        }

        #contents {
            width: 400px;
            height: 100%;
        }

        #contents .banner {
            width: 100%;
            height: 15%;
            background-color: #ff85c6;
        }

        #contents .notice {
            width: 100%;
            height: 35%;
            background-color: #ffbbea;
        }

        #contents .gallery {
            width: 100%;
            height: 35%;
            background-color: #ffa0e2;
        }

        #contents .link {
            width: 100%;
            height: 15%;
            background-color: #e29fff;
        }

        #slider {
            width: calc(100% - 600px);
            height: 100%;
            background-color: #ed86ff;
        }

        #footer {
            width: 100%;
            display: flex;
        }

        #footer .footer1 {
            width: 20%;
            height: 120px;
            background-color: #ebbcf3;
        }

        #footer .footer2 {
            width: 80%;
        }

        #footer .footer2 .footer2-1 {
            width: 100%;
            height: 60px;
            background-color: #f3a0e0;
        }

        #footer .footer2 .footer2-2 {
            width: 100%;
            height: 60px;
            background-color: #d5b3d7;
        }

        /* slider */
        .sliderWrap {
            position: relative;
            height: 100%;
        }

        /* .sliderWrap > div {
            display: none;
        }
        .sliderWrap > div:first-child {
            display: block;
        } */
        .sliderWrap .slider {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-repeat: no-repeat;
            background-position: center;
            background-size: cover;
        }

        .sliderWrap .slider.s1 {
            background-image: url(https://webstoryboy.github.io/webstoryboy/w_webd/slider/slider04.jpg);
        }

        .sliderWrap .slider.s2 {
            background-image: url(https://webstoryboy.github.io/webstoryboy/w_webd/slider/slider05.jpg);
        }

        .sliderWrap .slider.s3 {
            background-image: url(https://webstoryboy.github.io/webstoryboy/w_webd/slider/slider06.jpg);
        }

        .sliderWrap .slider span {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(255, 255, 255, 0.4);
            padding: 10px 20px;
        }
    </style>
</head>

<body>
    <div id="wrap">
        <main id="main">
            <header id="header">
                <h1></h1>
                <nav></nav>
            </header>
            <!-- //header -->

            <section id="contents">
                <div class="banner"></div>
                <div class="notice"></div>
                <div class="gallery"></div>
                <div class="link"></div>
            </section>
            <!-- //contents -->

            <article id="slider">
                <div class="sliderWrap">
                    <div class="slider s1">
                        <span>이미지1</span>
                    </div>
                    <div class="slider s2">
                        <span>이미지2</span>
                    </div>
                    <div class="slider s3">
                        <span>이미지3</span>
                    </div>
                </div>
            </article>
            <!-- //slider -->
        </main>
        <!-- //main -->
        <footer id="footer">
            <div class="footer1"></div>
            <div class="footer2">
                <div class="footer2-1"></div>
                <div class="footer2-2"></div>
            </div>
        </footer>
        <!-- //footer -->
    </div>
    <!-- //wrap -->

    <script>
        window.onload = function () {
            let currentIndex = 0;   //현재 이미지   
            const slider = document.querySelectorAll(".slider"); //각각의 이미지들
            slider.forEach(el => el.style.opacity = "0");   //모든 이미지 투명도 0
            slider[0].style.opacity = 1;    //첫번째 이미지는 투명도 1

            setInterval(() => {
                let nextIndex = (currentIndex + 1) % slider.length;

                slider[currentIndex].style.opacity = "0";
                slider[nextIndex].style.opacity = "1";
                slider.forEach(el => el.style.transition = "all 1s");

                currentIndex = nextIndex;
            }, 3000);
        }
    </script>
</body>

</html>


오른쪽에 있는 총 3개의 이미지가 서서히 생기는 이미지 슬라이드 였습니다.

This post is licensed under CC BY 4.0 by the author.