WordPressを組み込んだサイトにおいてSwiperを用いて、モーダルの中にスライダーが入っているというを作っているのですが、
Uncaught TypeError: swiper.slideTo is not a function at HTMLLIElement.<anonymous>
というエラーが出てしまい、どうすればいいのか分かりません。
ちなみに、jsのswiper.slideToという表記をなくせば、モーダルは表示されますが、意図したスライドが出てこないという状況です。何が悪いのでしょうか?
教えてくださると嬉しいです。
PHP
<dl class="p-event_article__row"> <dt class="p-event_article__ttl"><?php the_sub_field('title'); ?></dt> <?php $gallery = get_sub_field('gallery'); if( $gallery ){ ?> <!-- ▼ モーダルコンテンツ ▼ --> <dd class="p-event_article__ctn"> <!-- ▼ コンテンツ ▼ --> <ul class="p-event_article__img"> <?php foreach ( $gallery as $key => $img ) { ?> <li class="js-open-modal modal-cell" data-slide-index="<?php $i++; echo $i; ?>"> <img src="<?php echo $img; ?>" alt="<?php the_title(); ?>"> </li> <?php } ?> </ul> <!-- ▼ モーダル ▼ --> <div class="modal" id="modal"> <div class="modal__overlay js-close-modal"></div> <div class="modal__content"> <button class="modal__close-btn js-close-modal" aria-label="閉じる">×</button> <!-- スライダー --> <div class="swiper modal__slider"> <div class="swiper-wrapper"> <?php foreach ( $gallery as $key => $img ) { ?> <div class="swiper-slide modal__slide"> <img src="<?php echo $img; ?>" alt="<?php the_title(); ?>"> </div> <?php } ?> </div> <div class="swiper-button-prev"></div> <div class="swiper-button-next"></div> </div> </div> </div> </dd> <?php } ?> </dl>
CSS
.modal { position: fixed; top: 0; left: 0; width: 100%; height: 100vh; padding: 30px; display: flex; align-items: center; justify-content: center; transition: opacity 0.3s; pointer-events: none; opacity: 0; z-index: 100; background-color: rgba(120, 123, 131, 0.8); } .modal.is-active { opacity: 1; pointer-events: auto; } .modal__overlay { position: absolute; width: 100%; height: 100%; cursor: pointer; } .modal__content { position: relative; background-color: #fff; width: 100%; max-width: 900px; padding: 20px; } .modal__close-btn { position: absolute; right: 0; top: 0; width: 40px; height: 40px; background: #fff; border: 1px solid #ccc; cursor: pointer; z-index: 10; } .modal-cell { cursor: pointer; } .modal-cell:hover { opacity: 0.6; }
JavaScript
//モーダル修正 window.addEventListener("DOMContentLoaded", () => { // モーダルを取得 const modal = document.getElementById("modal"); // モーダルを表示するボタンを全て取得 const openModalBtns = document.querySelectorAll(".js-open-modal"); // モーダルを閉じるボタンを全て取得 const closeModalBtns = document.querySelectorAll(".js-close-modal"); // Swiperの設定 const swiper = new Swiper(".swiper", { loop: true, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, spaceBetween: 30, }); // モーダルを表示するボタンをクリックしたとき openModalBtns.forEach((openModalBtn) => { openModalBtn.addEventListener("click", () => { const modalIndex = openModalBtn.dataset.slideIndex; swiper.slideTo(modalIndex); modal.classList.add("is-active"); }); }); // モーダルを閉じるボタンをクリックしたとき closeModalBtns.forEach((closeModalBtn) => { closeModalBtn.addEventListener("click", () => { modal.classList.remove("is-active"); }); }); });
まだ回答がついていません
会員登録して回答してみよう