[Rails] Swiperを使ったスライダー機能

学習記録

swiperとは

jQueryに依存すること無く動作する最もモダンなモバイルタッチスライダーです。モバイルで使用知ることを想定しているため、スマホやタブレットでもスムーズにスライダー機能を実装することができます。

出典:https://swiperjs.com/demos#autoplay

npmでSwiperをインストール

$ npm install swiper

node_modulesディレクトリ配下に必要なファイルが作成されます。

読み込み設定

導入したnode_modules配下のファイルを読み込むようにするための設定をconfig/initializers/assets.rbに追記します。

Rails.application.config.assets.paths << Rails.root.join('node_modules')

application.css.scssapplication.jsのマニフェストファイルに、node_modulesの読み込みたいswiperファイルの名前を書きます。

@import 'swiper/swiper-bundle';
//= require swiper/swiper-bundle.js

※ ディレクトリのnode_modulesの部分は省略できるので、swiper/からファイルの名前を記入することができます。

swiperを実装

公式HPを参照し、HTMLとJSファイルを作成しましょう。現在(2021.11月)、swiperのバージョンは7系です。バージョンによって書き方が異なるので注意が必要です。 今回はヘッダーファイルにJSごと作成していきます。

header 
  .swiper
    .swiper-wrapper
      - if current_site.main_images.present?
        -current_site.main_images.each do |main_image|
          = image_tag main_image, class: 'swiper-slide'
      - else
        = image_tag '/images/cover.jpg', class: 'swiper-slide'
    .swiper-button-next    # ナビゲーションボタン(→)
    .swiper-button-prev    # ナビゲーションボタン(←)
    .swiper-pagination     # ページネーション

  .container.blog-title
    h1 = link_to current_site.name, root_path
    p.lead = current_site.subtitle

javascript:
  $(document).ready(() => {                   // 画像などを除いて、HTML=DOMの読み込みが終わったら関数の中の処理を実行する
    const swiper = new Swiper('.swiper', {    // クラス指定
      // Optional parameter
      spaceBetween: 30,       // スライド間の幅を指定
      centeredSlides: true,   // 中央寄せにする
      autoplay: {             
        delay: 3000,          // 切り替わり速度
        disableOnInteraction: false,     // ユーザーがスライダーを操作したあと、自動再生が止まらなくなる
      },

      // If we need pagination
      pagination: {
        el: ".swiper-pagination",
        clickable: true,
      },

      // Navigation arrows
      navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
      },

      // And if we need scrollbar
      scrollbar: {
        el: '.swiper-scrollbar',
      },
    })
  });

必要があればCSS設定し、swiperのデザインを調整しましょう。

.swiper {
  width: 600px;
  height: 300px;
  object-fit: cover;
}

参考記事

Swiper - The Most Modern Mobile Touch Slider
Swiper is the most modern free mobile touch slider with hardware accelerated transitions and amazing native behavior.

コメント

タイトルとURLをコピーしました