UIkitのモーダル内でSwiperを実行する。
要件
- .btn1 .btn2 .btn3 …クリック → モーダルが開く
- モーダル → UIkit の uk-modal
- Swiper → next/prev ボタン + サムネイル連動
- クリックしたボタンに対応したスライドを初期表示
- モーダルを閉じた時、Swiper をリセット
コード
HTML
CSS
.swiper {
width: 600px;
max-width: 90vw;
margin: 10px auto;
}
.swiper-slide img {
width: 100%;
display: block;
}
.thumb-swiper {
height: 80px;
box-sizing: border-box;
padding: 10px 0;
}
.thumb-swiper .swiper-slide {
width: auto;
opacity: 0.4;
cursor: pointer;
}
.thumb-swiper .swiper-slide-thumb-active {
opacity: 1;
border: 2px solid #0077ff;
}
JS
let mainSwiper, thumbSwiper;
function initSwipers(initialIndex) {
// サムネイル
thumbSwiper = new Swiper(".thumb-swiper", {
spaceBetween: 10,
slidesPerView: 3,
watchSlidesProgress: true,
});
// メインスライダー
mainSwiper = new Swiper(".main-swiper", {
spaceBetween: 10,
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev",
},
thumbs: {
swiper: thumbSwiper,
},
initialSlide: initialIndex,
});
}
function destroySwipers() {
if (mainSwiper) {
mainSwiper.destroy(true, true);
mainSwiper = null;
}
if (thumbSwiper) {
thumbSwiper.destroy(true, true);
thumbSwiper = null;
}
}
// ボタンクリック → モーダル表示 & Swiper初期化
document.querySelectorAll(".btn1, .btn2, .btn3").forEach((btn) => {
btn.addEventListener("click", function () {
const index = parseInt(this.dataset.slide, 10);
UIkit.modal("#modal").show();
// 少し待ってからSwiperを初期化(DOMが表示されてから)
setTimeout(() => {
initSwipers(index);
}, 100);
});
});
// モーダルクローズ時にSwiper破棄
UIkit.util.on("#modal", "hidden", function () {
destroySwipers();
});
coepen
See the Pen モーダルinスライダー by nerdspec (@nerdspec) on CodePen.