[javascript] Svelte에서 라이트박스(lightbox)를 구현하는 방법은 어떻게 되나요?
- 프로젝트에 Svelte 설치하기:
npx degit sveltejs/template svelte-app cd svelte-app
- 라이트박스 컴포넌트 생성하기:
src/
디렉토리에Lightbox.svelte
파일을 생성하고 다음과 같이 작성합니다:<script> export let images; let currentIndex = null; function openLightbox(index) { currentIndex = index; } function closeLightbox() { currentIndex = null; } function nextImage() { currentIndex = (currentIndex + 1) % images.length; } function prevImage() { currentIndex = (currentIndex - 1 + images.length) % images.length; } </script> <style> .lightbox { /* 라이트박스 스타일링 */ } </style> <div class="lightbox"> {#if currentIndex !== null} <div class="lightbox-overlay" on:click={closeLightbox}></div> <div class="lightbox-content"> <button on:click={prevImage}><</button> <img src={images[currentIndex]} alt="Image" /> <button on:click={nextImage}>></button> <button on:click={closeLightbox}>Close</button> </div> {/if} <ul> {#each images as image, i} <li> <img src={image} alt="Thumbnail" on:click={() => openLightbox(i)} /> </li> {/each} </ul> </div>
- 메인 애플리케이션 구성:
src/main.js
파일을 열고, 다음과 같이 수정합니다:import App from './App.svelte'; import Lightbox from './Lightbox.svelte'; const app = new App({ target: document.body, props: { images: [ 'image1.jpg', 'image2.jpg', 'image3.jpg', // 라이트박스에 사용할 이미지 경로 추가 ] } }); const lightbox = new Lightbox({ target: document.body, props: { images: app.props.images } }); export default app;
- 애플리케이션 실행:
npm run dev
명령어로 애플리케이션을 실행하고,/lightbox
경로로 접속하여 라이트박스가 구현된 것을 확인할 수 있습니다.
이제 Svelte를 사용하여 간단하게 라이트박스를 구현할 수 있습니다. 다른 필요에 따라 스타일링이나 기능을 추가로 수정할 수 있습니다.