← レベル2 – ウィザード

レッスン 5/8 ⏱ 35 分

ビューア付きフォトギャラリー

写真をクリックすると画面いっぱいに拡大。要素のグループを扱う方法を学ぼう。

どう動くか

レベル1のギャラリーをアップグレード:小さい写真をクリックすると、暗い背景の上に大きい版が全画面表示(lightbox と呼ぶ)。もう一度クリックで閉じる。

見てみよう:lightbox

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. 例に従って lightbox を追加。レベル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");
});

さらに2つ:function showPhoto(number) {...} は名前付き関数——どこからでも名前で呼べるコードの包み。photos[current] はリストから位置で項目を取り出す(数え始めはゼロ!)。

プロジェクトのアイデア:🏫 学校イベントの写真 · 🙋 作品と冒険 · 🌍 旅行の写真(lightbox が本当に輝く!)· ⚽ 試合の瞬間。

確認: 写真をクリック → 暗い背景で拡大。もう一度クリック → 閉じる。ボーナスなら矢印で移動、Escape で閉じる。プロサイトのギャラリーと同じ——中身が分かった。

このレッスンのまとめ