Splide
サムネイルと連動するスライダー(ギャラリー)
script
const splide = new Splide('.splide', {
type: 'loop', //初期値'slide' | 'fade'
perPage: 1, //表示枚数
pagination: false, //ページネーション
})
// リスト要素をクラス名ですべて取得
const thumbnails = document.querySelectorAll('#thumbnails button');
let current; // 現在のサムネイルを保持するための変数
thumbnails.forEach((el, i) => {
initThumbnail(thumbnails[i], i);
})
// それぞれのリスト要素を初期化するための関数
function initThumbnail(thumbnail, index) {
thumbnail.addEventListener('click', function() {
splide.go(index);
});
}
splide.on('mounted move', function() {
if (current) {
current.classList.remove('is-active');
}
// Splide#indexは現在アクティブなスライドのインデックスを返す
const thumbnail = thumbnails[splide.index];
if (thumbnail) {
thumbnail.classList.add('is-active');
current = thumbnail;
}
});
splide.mount();
CSS
.slide-block {
width: min(100%, 800px);
margin: 0 auto;
}
.splide img {
width: 100%;
aspect-ratio: 16 / 9;
object-fit: cover;
}
.main-carousel {
margin-bottom: 20px;
}
.thumbnails {
display: flex;
justify-content: center;
gap: 10px;
margin: 0 auto;
}
.thumbnails button {
width: 100px;
cursor: pointer;
margin: 0;
padding: 0;
}
.thumbnails img {
width: 100%;
opacity: 0.5;
}
.thumbnails button.is-active img {
opacity: 1.0;
}
.thumbnails button:focus-visible {
outline: auto;
}
HTML





