본문 바로가기

HTML 예제

웹 캐러셀: 이미지 슬라이드 쇼와 버튼으로 제어하는 웹 캐러셀

반응형

웹 캐러셀 (Image Carousel)을 만들기 위한 단계별 설명과 코드를 제공해드리겠습니다.

HTML 파일 생성하기 (index.html):
먼저, HTML 파일을 생성하고 내용을 추가합니다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>웹 캐러셀</title>
</head>
<body>
    <div class="carousel-container">
        <button id="prev-button">이전</button>
        <div class="carousel">
            <img src="image1.jpg" alt="Image 1">
            <img src="image2.jpg" alt="Image 2">
            <img src="image3.jpg" alt="Image 3">
            <!-- 원하는 이미지를 추가하세요 -->
        </div>
        <button id="next-button">다음</button>
    </div>
    <script src="script.js"></script>
</body>
</html>

 


CSS 스타일 시트 생성하기 (styles.css):
CSS로 스타일을 추가합니다.


/* styles.css */

body {
    font-family: Arial, sans-serif;
    text-align: center;
    background-color: #f0f0f0;
    margin: 0;
    padding: 0;
}

.carousel-container {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    margin-top: 20px;
}

.carousel {
    display: flex;
    overflow: hidden;
}

.carousel img {
    width: 100%;
    max-width: 600px;
    height: auto;
    transition: transform 0.5s ease-in-out;
}

button {
    font-size: 18px;
    padding: 10px 20px;
    background-color: #007bff;
    color: #fff;
    border: none;
    cursor: pointer;
    transition: background-color 0.3s;
}

button:hover {
    background-color: #0056b3;
}

 


JavaScript 파일 생성하기 (script.js):
웹 캐러셀의 동작을 구현할 JavaScript 파일을 생성합니다.


// script.js
const carousel = document.querySelector(".carousel");
const images = document.querySelectorAll(".carousel img");
const prevButton = document.getElementById("prev-button");
const nextButton = document.getElementById("next-button");

let currentImageIndex = 0;

function showImage(index) {
    images.forEach((image) => {
        image.style.transform = `translateX(-${index * 100}%)`;
    });
}

prevButton.addEventListener("click", () => {
    currentImageIndex = (currentImageIndex - 1 + images.length) % images.length;
    showImage(currentImageIndex);
});

nextButton.addEventListener("click", () => {
    currentImageIndex = (currentImageIndex + 1) % images.length;
    showImage(currentImageIndex);
});

showImage(currentImageIndex);

 


결과 확인:
웹 브라우저에서 index.html 파일을 열면 이미지 슬라이드 쇼와 버튼으로 제어하는 웹 캐러셀을 볼 수 있습니다.

반응형