WEBデザイナー&コーダーのYJ2222です。
JSを使ったスライダープラグインSwiperについてのメモです。
経緯と概要
今回は最新(2022/2/3時点)の事についてではなく、古いVerのものになります。
経緯としてはコード改修案件で古いVerのまま実装しなくてはならなくて検索に困ったので自分用にまとめることにしました。
わざわざ古いVerを使うことはないかと思いますが、もし同じ境遇の方いたら助けになれば思います。
ただ詳しくは書けないので、参考程度にお願いします。
▼正式マニュアル(最新版)
https://swiperjs.com/get-started
▼Ver3.4.1で参考にした記事
https://www.willstyle.co.jp/blog/724/
完成計コード
先に完成形を載せていきます。
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.1/css/swiper.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.1/js/swiper.min.js"></script>
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide"><img src="../img/store_image_1.jpg" alt=""></div>
<div class="swiper-slide"><img src="../img/store_image_2.jpg" alt=""></div>
<div class="swiper-slide"><img src="../img/store_image_3.jpg" alt=""></div>
</div>
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
</div>
※画像URL等は適宜変えてください。
.swiper-container {
width: 100%;
max-width: 800px;
}
.swiper-slide img {
width: 100%;
}
.swiper-button-prev,
.swiper-button-next {
background-color: rgba(0, 0, 0, 0.5);
width: 50px !important;
height: 50px !important;
}
.swiper-button-prev:hover,
.swiper-button-next:hover {
background-color: rgba(0, 0, 0, 1);
}
.swiper-button-prev {
background-image: url(../img/chevron-left.svg) !important;
}
.swiper-button-next {
background-image: url(../img/chevron-right.svg) !important;
}
window.onload = function() {
var mySwiper = new Swiper('.swiper-container',{
loop: true,
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
speed: 1000,
});
}
最新版との変更点
CDNが違う
当たり前といえば、当たり前ですが、Verの数字が違いますよ~レベルじゃなく変わってますね^^;
コンテナ名が違う
スライダーをかこってる大元のクラス名が違います。
旧:.swiper-container
新:.swiper
JSの記述が違う
ここが結構大きいかもしれません。今回の例で行くと左右のアイコンの表示部分です。最新版だと配列が多次元になっているのと、そもそもキーの名前が変わってます。
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
pagination
などもこのような感じで変わってました。
よく使いそうな、direction
(方向)やspeed
、loop
などは変わってなかったみたいです。
まとめ
冒頭にも書きましたが、まぁわざわざ古いVerを使うことはないのでこれから実装する人には要らない情報です。
ただ案件によってはVerそのままでってなることもあるのでその時にお役に立てればと思います。