// 1) // モーダルを開く際のボタン(htmlのタグ)に下記をつける // .js-modal-btn // data-modal="modal-01" // 2)開きたいモーダルのidを上記のdata-modal="modal-01"と同じにする // // // モーダル document.addEventListener("DOMContentLoaded", function() { const modalBtns = document.querySelectorAll(".js-modal-btn"); const modalContents = document.querySelectorAll(".modal-container"); const modalBgs = document.querySelectorAll(".modal-bg"); const modalCloses = document.querySelectorAll(".modal-close"); const total = modalContents.length; let currentIndex = 0; // 各モーダルにカウンター要素を自動追加 modalContents.forEach(modal => { const btnContainer = modal.querySelector(".modal-btn"); if (btnContainer && !btnContainer.querySelector(".modal-counter")) { const counter = document.createElement("p"); counter.classList.add("modal-counter","en"); const prevBtn = btnContainer.querySelector(".modal-btn-prev"); const nextBtn = btnContainer.querySelector(".modal-btn-next"); if (prevBtn && nextBtn) { btnContainer.insertBefore(counter, nextBtn); } else { btnContainer.appendChild(counter); } } }); // モーダルを開く modalBtns.forEach(btn => { btn.addEventListener("click", function() { const modalId = btn.getAttribute("data-modal"); const modalItem = document.querySelector("#" + modalId); if (!modalItem) return; currentIndex = [...modalContents].indexOf(modalItem); openModal(modalItem); }); }); // モーダルを開く関数 function openModal(modalItem) { modalContents.forEach(m => m.classList.remove("on")); modalItem.classList.add("on"); document.body.classList.add("on"); updateCounter(); } // カウンター更新 function updateCounter() { const modalItem = modalContents[currentIndex]; const counter = modalItem.querySelector(".modal-counter"); if (counter) { counter.textContent = (currentIndex + 1).toString().padStart(2, "0") + "/" + total.toString().padStart(2, "0"); } } // 閉じる処理 [...modalBgs, ...modalCloses].forEach(el => { el.addEventListener("click", function() { modalContents.forEach(m => m.classList.remove("on")); document.body.classList.remove("on"); }); }); // 前後ボタン modalContents.forEach((modal, i) => { const prevBtn = modal.querySelector(".modal-btn-prev"); const nextBtn = modal.querySelector(".modal-btn-next"); if (prevBtn) { prevBtn.addEventListener("click", function(e) { e.stopPropagation(); currentIndex = (currentIndex - 1 + total) % total; openModal(modalContents[currentIndex]); }); } if (nextBtn) { nextBtn.addEventListener("click", function(e) { e.stopPropagation(); currentIndex = (currentIndex + 1) % total; openModal(modalContents[currentIndex]); }); } }); // ページ読み込み時、既に開いているモーダルにもカウンターを設定 modalContents.forEach((modal, index) => { if (modal.classList.contains("on")) { currentIndex = index; updateCounter(); } }); });