LoginSignup
4
1

More than 3 years have passed since last update.

MaterializecssのCarouselを使用して、3秒ごとに画像が自動で切り替わるページを作る

Last updated at Posted at 2019-07-08

概要

TECH::EXPERTのカリキュラムでオリジナルのミニアプリを作成する機会があり、
その一部のページでMaterializecssのCarouselを使用し、3秒ごとに画像が切り替わるページを作成したので紹介します。

MaterializecssのCarouselとは

画像をくるくると回せる機能です。
Image from Gyazo
https://materializecss.com/carousel.html

自分が作成したページ紹介

Image from Gyazo

作成する前提

MaterializecssがCDNで読み込めている

編集するファイル

・ビューファイル
・CSSファイル
・jsファイル

ビューファイル

about.html.erb
<section class="about-main" >
  <div class="carousel carousel-slider" data-indicators="true" id="big3" >
    <div class="carousel-fixed-item">
      <div class="container">
        <h1 class="white-text">Work Hard See Result</h1>
      <% if user_signed_in? %>
        <a class="btn waves-effect white black-text darken-text-2" href="/" target="_blank">HOME</a>
      <%else%>
        <a class="btn waves-effect white black-text darken-text-2" href="/users/sign_in" target="_blank">Log in</a>
      <%end%>
      </div>
    </div>
    <div class="carousel-item big3pic" id="benchpress">
      <div class="container">
        <h3 class="white-text">Bench Press</h3>
        <p class="white-text">chest</p>
      </div>
    </div>
    <div class="carousel-item big3pic" id="deadlift">
      <div class="container">
        <h3 class="white-text">Dead Lift</h3>
        <p class="white-text">back</p>
      </div>
    </div>
    <div class="carousel-item big3pic"  id="squat">
      <div class="container">
        <h3 class="white-text">Squat</h3>
        <p class="white-text">legs</p>
      </div>
    </div>
  </div>
</section>

"carousel carousel-slider" を用いました。
"carousel-fixed-item"は固定して表示したいものを書きます。
"carousel carousel-item"の部分がそれぞれの画像のクラスです。

CSSファイル

style.css
#big3{
  height: 100vh;
}
#benchpress{
  background-image: url('benchpress.jpg');
  background-size: 100%;
}
#deadlift{
  background-image: url('deadlift.jpg');
  background-size: 100%;
}
#squat{
  background-image: url('squat.jpg');
  background-size: 100%;
}

それぞれidを付与してるので、idによって画像を変更してください。

jsファイル

about.js
$(document).ready(function(){
  $('#big3').carousel(
  {
    dist: 0,
    padding: 0,
    fullWidth: true,
    indicators: true,
    duration: 100,
  }
  );
  autoplay()
  function autoplay() {
      $('#big3').carousel('next');
      autoplay: true,
      setTimeout(autoplay, 3000);
  }
});

autoplayの関数を定義してます。
id=big3に対して3000ミリ秒で次のcarousel-itemを
表示するように設定してます。

オプションは下記を参照しました。

  • [1] dist: 0, => 遠近ズーム0
  • [2] padding: 0, => 中央以外の項目の余白0
  • [3] fullWidth: true, => carouselを全幅のスライダーへ
  • [4] indicators: true, => インジケータを表示
  • [5] duration: 100, => 次のスライドへ移動しきるまでの時間100ミリ秒

Image from Gyazo

4
1
1

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