Swiperで背景画像をスライドさせる
MEMORANDUM
Swiper
Swiper
BgSwitcherで背景画像をスライドさせるのと同じような表示をSwiperでもやってみた。厳密には背景ではなく画像をスライドさせてその上にタイトルを表示させただけ。
SwiperはjQueryを使わずに様々なスライドの設定ができるツール。オプションの設定変更でいろんな動作が設定できる。まずはswiper-bundle.min.cssとswiper-bundle.min.jsを読み込ませる。もしくはダウンロードして格納先を指定する。
<link rel="stylesheet" href="https://unpkg.com/swiper@7/swiper-bundle.min.css"/>
<script src="https://unpkg.com/swiper@7/swiper-bundle.min.js"></script>
<body>〜</body>内の表示したい場所に以下のHTMLコードと設定スクリプトを並べて記述。CSSも設定する。
<!-- Slider main container -->
<div class="container-swiper">
<!-- Additional required wrapper -->
<div class="swiper-wrapper">
<!-- Slides ここに表示させたい画像を設定 -->
<div class="swiper-slide"><img src="サイトURL/img/bgimg01.png"></div>
<div class="swiper-slide"><img src="サイトURL/img/bgimg02.png"></div>
<div class="swiper-slide"><img src="サイトURL/img/bgimg03.png"></div>
</div>
<!-- タイトルを表示 -->
<div class="title">MEMORANDUM<br>jQuery<br>BgSwitcher.js</div>
<!-- If we need paginationページネーションを表示させる場合は記載 -->
<div class="swiper-pagination"></div>
<!-- 以下はナビボタンやスクロールとか必要があれば設定 今回は表示しないのでコメントアウト -->
<!-- If we need navigation buttons
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div> -->
<!-- If we need scrollbar
<div class="swiper-scrollbar"></div> -->
</div>
動作の設定やオプションはスクリプト上で設定する。必要最小限の設定しかしていないのでもっと細かな設定をしたい場合は以下のリンク先を参照。
<script>
var mySwiper = new Swiper('.container-swiper', {
// スライドの間隔ー単位はpx
spaceBetween: 0,
// 表示されるスライドの枚数
slidesPerView: 1,
// スライドの高さに合わせてSwiperの高さを変える
autoHeight: true,
// ループする
loop: true,
// スライドスピード
speed: 5000,
// エフェクト
effect: 'fade',
/*自動で再生する*/
autoplay: {
// スライドの動く間隔
delay: 10000,
// trueなら最後のスライドまで行ったら停止する。falseなら最初に戻る
stopOnLastSlide: false,
// trueなら触った後停止falseなら再生され続ける
disableOnInteraction: false,
// trueなら最後のスライドまで行ったら停止する。falseなら最初に戻る
reverseDirection: false
},
/*スライドボタン*/
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
},
/*ページネーション*/
pagination: {
el: '.swiper-pagination',
type: 'bullets',
clickable: true,
}
});</script>
スタイルシート。余分な設定があるかもしれないが。画像上の文字表示はもっといい方法があるかもしれない。
.container-swiper {
margin-left: auto;/*不要かも*/
margin-right: auto;/*不要かも*/
position: relative;/*相対配置*/
overflow: hidden;/*はみ出た部分隠す*/
}
.swiper-slide > img {
object-fit: cover; /*アスペクト比を維持しボックス全体を埋めるように拡大縮小 IE: not support */
width: 100%;
}
.swiper-pagination{
margin-bottom: 5px;/*ページナビゲーションの位置*/
}
.swiper-pagination-bullet {
background:#292F33!important;/*ページナビゲーションの色を変更*/
}
.container-swiper .title {/*スライド全面にタイトル表示する設定*/
position: absolute;/*絶対配置*/
text-align: center;
top: 50%; /*親要素を起点に上から50%*/
left: 50%; /*親要素を起点に左から50%*/
transform: translateY(-50%) translateX(-50%); /*要素の大きさの半分ずつを戻す*/
-webkit-transform: translateY(-50%) translateX(-50%);
z-index: 999;
color: #ccc;
font-family:'Montserrat', sans-serif;
font-size: 450%;
font-weight: 700;
line-height: 1.0em;
}
BgSwitcherとどっちがいいんだろ。jQueryをたくさん使いすぎていればこっちになるのかな。
NOTICES
- 記事内容は実装させたものがほとんどですが自己責任で参考にしてください。