この記事では、JavaScriptを使ってシンプルなフォトギャラリーを作る方法を説明します。画像をクリックして拡大表示したり、スライドのように切り替えたりすることができるフォトギャラリーは、ポートフォリオサイトやお店の紹介ページなどでよく使われています。
HTMLの準備
まずは、画像を並べるためのHTMLを書きます。
■index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>フォトギャラリー</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>フォトギャラリー</h1>
<div class="gallery">
<img src="p01.jpg" alt="写真1" class="thumb">
<img src="p02.jpg" alt="写真2" class="thumb">
<img src="p03.jpg" alt="写真3" class="thumb">
</div>
<div id="modal" class="modal">
<span id="closeBtn">×</span>
<img id="modalImage" class="modal-content">
</div>
<script src="script.js"></script>
</body>
</html>
上記では、画像3枚を表示するためのHTMLと、モーダル(拡大表示)用の要素を用意しています。
CSSで見た目を整える
次に、見た目を整えるCSSを用意します。
■style.css
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f9f9f9;
}
.gallery {
display: flex;
justify-content: center;
gap: 20px;
margin-top: 30px;
}
.thumb {
width: 150px;
cursor: pointer;
transition: transform 0.3s;
}
.thumb:hover {
transform: scale(1.1);
}
/* モーダル(画像拡大表示)用 */
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.8);
justify-content: center;
align-items: center;
}
.modal-content {
max-width: 80%;
max-height: 80%;
}
#closeBtn {
position: absolute;
top: 20px;
right: 30px;
color: white;
font-size: 40px;
cursor: pointer;
}
このCSSでは、サムネイル画像の表示と、クリックしたときに表示されるモーダルのスタイルを定義しています。
JavaScriptで動きを追加
最後に、JavaScriptで画像をクリックしたらモーダルを表示し、別の画像を見れるようにしましょう。
■script.js
// 全てのサムネイル画像を取得
const thumbnails = document.querySelectorAll('.thumb');
const modal = document.getElementById('modal');
const modalImage = document.getElementById('modalImage');
const closeBtn = document.getElementById('closeBtn');
// サムネイルがクリックされたらモーダル表示
thumbnails.forEach(function(thumb) {
thumb.addEventListener('click', function() {
modal.style.display = 'flex';
modalImage.src = this.src;
});
});
// 閉じるボタンでモーダルを非表示
closeBtn.addEventListener('click', function() {
modal.style.display = 'none';
});
// モーダル背景クリックでも閉じる
modal.addEventListener('click', function(e) {
if (e.target === modal) {
modal.style.display = 'none';
}
});
このコードでは、画像をクリックするとモーダルが表示され、拡大画像が見れるようになっています。また、背景や×ボタンをクリックすれば閉じるようにしています。
ファイルの配置
ファイルを以下のように配置します。
実行
1.「index.html」を表示します。
2.写真をクリックすると拡大表示されます。
まとめ
今回は、HTML・CSS・JavaScriptを使ってシンプルなフォトギャラリーを作る方法を説明しました。
このフォトギャラリーの特徴
・サムネイル画像の表示
・クリックで拡大(モーダル表示)
・閉じる機能付き
・CSSで簡単なエフェクト付き
ぜひ自分の作品ページやポートフォリオに取り入れてみてください。