1
2

More than 3 years have passed since last update.

Swiperを使ってスライダー機能の実装

Last updated at Posted at 2021-01-30

Swiper

Swiperとは

jQuery 不要でレスポンシブ及びタッチデバイス(スマホやタブレット)対応のスライダープラグイン Swiperを使うことで簡単にスライダーを実装することができる。

Image from Gyazo

[Swiper公式サイト https://swiperjs.com/]

Swiperのダウンロード方法

Swiperのダウンロードは様々あるが今回はnpmでSwiperをインストールするものとする。

1. Swiperのインストール

$ npm install swiper

コンソールでswiperをインストールする

2. node_modulesをassetsに追加

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

node_modulesをassetsに追加するためにconfig/initializers/assets.rbに上記を記入

3. Swiperをアプリに反映させる

app/assets/javascripts/application.js
//= require swiper/swiper-bundle.js

jsファイルにSwiperのコードを記述したら反映できるようにjsファイルに上記を記述する。

Swiperを記述する

Swiper公式リファレンスに沿って記述していく

Image from Gyazo

<!-- Slider main container -->
<div class="swiper-container">
  <!-- Additional required wrapper -->
  <div class="swiper-wrapper">
    <!-- Slides -->
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    <div class="swiper-slide">Slide 3</div>
    ...
  </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>

各スライド(Slide1,Slide2)に画像を貼ることでスライダーになる

Swiperの各オプション

縦スライドや自動スクロールなど様々なスライドオプションはjsファイルに記述することによって
しようを変えることができる

[参考 https://garigaricode.com/swiper/]

今回はslim形式で自動スクロールを実装する

Image from Gyazo

<!-- Slider main container -->
.swiper-container
  <!-- Additional required wrapper -->
  .swiper-wrapper
    <!-- Slides -->
    .swiper-slide
      Slide 1  (ここには画像をはる)
    .swiper-slide
      Slide 2 (ここには画像をはる)
    .swiper-slide
      Slide 3 (ここには画像をはる)
    .swiper-slide
      Slide 4 (ここには画像をはる)
  <!-- If we need pagination -->
  .swiper-pagination

  <!-- If we need navigation buttons -->
  .swiper-button-prev
  .swiper-button-next

  <!-- If we need scrollbar -->
  .swiper-scrollbar
var mySwiper = new Swiper('.swiper-container', {
    autoplay: {
        delay: 3000,
        stopOnLastSlide: false,
        disableOnInteraction: false,
        reverseDirection: false
        }
});

基本的に上のオプションのサイトをみながらコードを記述すると実装することができる。

1
2
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
1
2