LoginSignup
5
8

More than 3 years have passed since last update.

【Ruby on Rails】Skipprを使用した画像スライドショー

Posted at

目標

スライドショー.gif

開発環境

ruby 2.5.7
Rails 5.2.4.3
OS: macOS Catalina

前提

※ ▶◯◯ を選択すると、説明等が出てきますので、
  よくわからない場合の参考にしていただければと思います。

流れ

1 gemの導入
2 Skipprサイトからファイルをダウンロード
3 実際のコード

gemの導入

Railsでjqueryを使えるようにします。

Gemfile
gem 'jquery-rails'
ターミナル
$ bundle insatll
app/assets/javascripts/application.js
//= require jquery ←追加
//= require jquery_ujs ←追加
//= require activestorage
//= require turbolinks
//= require_tree .

Skipprサイトからファイルをダウンロード

公式サイト
http://austenpayan.github.io/skippr/

こちらのGithubをクリックし、ZIPファイルをダウンロードしてください。
スクリーンショット 2020-10-15 13.20.39.png
スクリーンショット 2020-10-15 13.22.35.png

解凍後、下記の通りに保存してください。

  • skippr.min.jsファイルは、app/assets/javascriptsフォルダに
  • skippr.cssファイルは、app/assets/stylesheetsフォルダに スクリーンショット 2020-10-15 13.25.43.png

実際のコード

app/assets/imagesにimage1.jpg〜image4.jpgを保存してください。

app/views/application.html.erb
<div id="box">
  <div id="images">
    <div class="image1"></div>
    <div class="image2"></div>
    <div class="image3"></div>
    <div class="image4"></div>
  </div>
</div>
app/assets/stylesheets/application.css
/* 高さを指定することにより画像が表示される */
#box{
  height: 600px;
}
.image1 {
  background-image: url(image1.jpg);
}
.image2 {
  background-image: url(image2.jpg);
}
.image3 {
  background-image: url(image3.jpg);
}
.image4 {
  background-image: url(image4.jpg);
}
app/assets/javascripts/application.js
$(document).ready(function () {
  $("#images").skippr({
    // スライドショーの変化 ("fade" or "slide")
    transition : 'slide',
    // 変化に係る時間(ミリ秒)
    speed : 1000,
    // easingの種類
    easing : 'easeOutQuart',
    // ナビゲーションの形("block" or "bubble")
    navType : 'block',
    // 子要素の種類("div" or "img")
    childrenElementType : 'div',
    // ナビゲーション矢印の表示(trueで表示)
    arrows : true,
    // スライドショーの自動再生(falseで自動再生なし)
    autoPlay : true,
    // 自動再生時のスライド切替間隔(ミリ秒)
    autoPlayDuration : 3000,
    // キーボードの矢印キーによるスライド送りの設定(trueで有効)
    keyboardOnAlways : true,
    // 一枚目のスライド表示時に戻る矢印を表示するかどうか(falseで非表示)
    hidePrevious : false
  });
});

まとめ

比較的簡単に導入できるものの、
bootstrapと組み合わせるとうまくいかないこともあるので、
その場合はこちらを参考にしてください。
【Ruby on Rails】bootstrap4のcarouselをeachメソッドを使いスライドショーを実装

またtwitterではQiitaにはアップしていない技術や考え方もアップしていますので、
よければフォローして頂けると嬉しいです。
詳しくはこちら https://twitter.com/japwork

5
8
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
5
8