HTML
<div class="container">
<h1>Swiper sample 07</h1>
<div class="swiper-container" id="mySlider">
<div class="swiper-wrapper">
<div class="swiper-slide"><img src="images/sample_01.png" alt=""></div>
<div class="swiper-slide"><img src="images/sample_02.png" alt=""></div>
<div class="swiper-slide"><img src="images/sample_03.png" alt=""></div>
<div class="swiper-slide"><img src="images/sample_04.png" alt=""></div>
<div class="swiper-slide"><img src="images/sample_05.png" alt=""></div>
<div class="swiper-slide"><img src="images/sample_06.png" alt=""></div>
</div><!-- end of .swiper-wrapper -->
<div class="swiper-pagination swiper-pagination-white"></div>
<div class="swiper-button-prev swiper-button-white"></div>
<div class="swiper-button-next swiper-button-white"></div>
</div><!-- end of .swiper-container -->
</div><!-- end of .container -->
CSS
.container {
margin: auto;
max-width: 1400px;
}
.swiper-slide img {
width: 100%;
height: auto;
}
@media(min-width: 961px) {
.swiper-wrapper {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.swiper-slide {
max-width: 400px;
padding: 0 5px;
}
.swiper-button-prev, .swiper-button-next, .swiper-pagination {
display: none;
}
}
JavaScript
<script>
let mySwiperX; //Swiperインスタンスを格納する変数の宣言
let screenWidth; //画面幅の値を格納する変数の宣言
let swiperElement = document.getElementById("mySlider"); //コンテナ要素
let options = { //スライダーの初期化のオプション
loop: true,
centeredSlides : true,
pagination: {
el: '.swiper-pagination',
clickable: true,
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
slidesPerView: 1,
spaceBetween: 0,
breakpoints: {
641: {
slidesPerView: 2,
spaceBetween: 10
},
}
};
function initSwiper() {
if(swiperElement){ //コンテナ要素があれば
screenWidth = window.innerWidth;
if(screenWidth < 961 && !mySwiperX ) {
mySwiperX = new Swiper('#mySlider', options); //スライダーの初期化
} else if (screenWidth >= 961 && mySwiperX ) {
mySwiperX.destroy(true, true); //スライダーを破棄
mySwiperX = null;
}
}
}
initSwiper();
window.addEventListener('resize',initSwiper);
</script>