← 레벨 2 – 위저드

수업 5/8 ⏱ 35 분

뷰어가 있는 사진 갤러리

사진을 클릭하면 사진이 더 커지며 전체 화면을 채웁니다. 요소 그룹을 사용하여 작업하는 방법을 배우게 돼.

작동 방식

갤러리를 레벨 1에서 업그레이드할 거야. 작은 사진을 클릭하면 어두운 배경의 전체 페이지에 큰 버전이 열어(라이트박스라고 함). 다시 클릭하면 닫힙니다.

보여줄게: 라이트박스

HTML – 갤러리 아래에 “확대 창”을 추가해(처음에는 숨겨짐).

<div class="gallery">
  <img src="images/p1.jpg" alt="First photo">
  <img src="images/p2.jpg" alt="Second photo">
  <img src="images/p3.jpg" alt="Third photo">
</div>

<div id="lightbox" class="hidden">
  <img id="lightbox-photo" src="" alt="">
</div>

CSS – 전체 화면을 덮는 창:

#lightbox {
  position: fixed;          /* stuck over the whole window */
  inset: 0;                 /* 0 from every edge = the whole area */
  background-color: rgba(0, 0, 0, 0.85);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

#lightbox img {
  max-width: 90%;
  max-height: 90%;
}

.hidden {
  display: none !important; /* hide completely */
}

JavaScript - 이제 새로운 기능이 추가되었어. 모든 사진을 한 번에 작업할 수 있어.

const photos = document.querySelectorAll(".gallery img");
const lightbox = document.getElementById("lightbox");
const lightboxPhoto = document.getElementById("lightbox-photo");

// For every photo in the gallery: show it big on click
photos.forEach((photo) => {
  photo.addEventListener("click", () => {
    lightboxPhoto.src = photo.src;
    lightboxPhoto.alt = photo.alt;
    lightbox.classList.remove("hidden");
  });
});

// Clicking anywhere in the lightbox closes it
lightbox.addEventListener("click", () => {
  lightbox.classList.add("hidden");
});

새로운 내용:

네 차례 💪

  1. 예시에 따라 웹사이트에 라이트박스를 추가해. 이미 레벨 1의 갤러리가 있어. 선택기(.gallery img) 수업과 일치해.
  2. 용감한 사람들을 위한 업그레이드 – 화살표로 탐색:
보너스: 다음/이전 사진으로 이동스크립트 확장 – 현재 열려 있는 사진을 기억해.
const photos = document.querySelectorAll(".gallery img");
const lightbox = document.getElementById("lightbox");
const lightboxPhoto = document.getElementById("lightbox-photo");
let current = 0;

function showPhoto(number) {
  // Handle wraparound: after the last photo comes the first again
  if (number < 0) number = photos.length - 1;
  if (number >= photos.length) number = 0;

  current = number;
  lightboxPhoto.src = photos[current].src;
  lightboxPhoto.alt = photos[current].alt;
}

photos.forEach((photo, index) => {
  photo.addEventListener("click", () => {
    showPhoto(index);
    lightbox.classList.remove("hidden");
  });
});

lightbox.addEventListener("click", () => {
  lightbox.classList.add("hidden");
});

// Navigate with the keyboard
document.addEventListener("keydown", (event) => {
  if (lightbox.classList.contains("hidden")) return;

  if (event.key === "ArrowRight") showPhoto(current + 1);
  if (event.key === "ArrowLeft") showPhoto(current - 1);
  if (event.key === "Escape") lightbox.classList.add("hidden");
});

두 가지 새로운 사항: **function showPhoto(number) {...}**는 명명된 함수야. 이름으로 어디에서나 실행할 수 있는 코드 패키지야. 그리고photos[current]위치에 따라 목록에서 항목을 가져옵니다(계산은 0부터 시작해!).프로젝트 아이디어: 🏫 학교 행사 사진 · 🙋 창작물과 모험 · 🌍 여행 사진(라이트박스가 정말 빛나는 곳야!) · ⚽ 경기 순간.

✅
**직접 확인해 보세요:** 사진을 클릭하면 → 어두운 배경에서 사진이 커집니다. 다시 클릭하면 → 닫힙니다. 보너스를 사용하면 화살표로 탐색하고 Escape로 닫을 수도 있어. 이것이 바로 갤러리가 전문 웹사이트에서 작동하는 방식야. 이제 내부 내용을 알 수 있어.

이번 수업에서 배울 점

-querySelectorAll()CSS 선택기와 일치하는 모든 요소를 ​​찾어.forEach하나씩 거쳐갑니다.