0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swiper.js(Ver6系)でタブの横スクロールを実現する

Last updated at Posted at 2020-12-23

デモ

なんか知らないうちにSwiperのバージョンめっちゃ上がりましたね…
私の知っている時はVer3ぐらいだったと思いますが、いつの間にかVer6に…
WEBの進化はやすぎわろた。

オプション名とか引数の並び順とかも結構変わってたので、
改めて実装しました。

ミソ

  var tabSwiper = new Swiper('.tabs-box', tabSwiperOptions);
  var boardSwiper = new Swiper('.board-box', boardSwiperOptions);

  tabSwiper.slides.each(function(event, index){
    $(this).on("click", function(){
      $(".tabs .tab").removeClass("selected"); // init
      $(this).addClass("selected");

      boardSwiper.slideTo(index, 500, false);
    });
  });

タブ要素はページネーションを使うのではなく、スライダーとして生成します。
コンテンツも同じくスライダーとして生成します。

この時、これら二つのスライダー要素の数は同じである必要があります。

任意のタブ要素(スライダー)をクリックすると、
タブ要素(スライダー)のインデックス番号が取得できます。

このインデックス番号を利用して、
タブ要素のクリック時に、コンテンツも同じインデックス番号のスライダーに移動させることで、
タブ移動が実現します。

また、ボード側のスワイプで移動しないように noSwiping:true を設定しています。
動かしたくないスライダーに swiper-no-swiping クラスをつけることで、動かないようにできます

<div class="swiper-container board-box">
  <div class="swiper-wrapper boards swiper-no-swiping">
    <div class="swiper-slide board">内容 1</div>
    <div class="swiper-slide board">内容 2</div>
    ...
  </div>
</div>

ボード側のスワイプでも動くようにしたければ、以下のページの実装を参考にしてください(別作者)

実装上の注意

CSSで、内容部分の背景色に白色を明示的に設定していますが、
これは消さないでください。
背景色がないと、透過扱いになるのか、
タブを変更した際に後ろにあるコンテンツと被ります

.boards .board {
  background: #FFF;
  text-align: center;
}

依存するライブラリ

  • jQuery
  • Swiper.js
  • Swiper.css

参考サイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?