▲TOPへ戻る

【javascript】イメージスライダー(image slider)の作り方

以下のようなイメージスライダーのコードを紹介します。

HTML

ポイントは画像1枚目にクラスactive,2枚目にクラスnextを指定しておくことです。

 <div class="slider">
    <div class="images">
    <!-- お好みの画像を指定。何枚でも可。 -->
      <img
        src="https://gxy-life.com/images/blog/202102/4 (3).JPG" 
        class="active"/>  <!-- 最初にクラスactiveを指定 -->
      <img
        src="https://gxy-life.com/images/blog/202102/1h_01.JPG"
        class="next"/>  <!-- 最初にクラスnextを指定 -->
      <img src="https://gxy-life.com/images/blog/202103/4 (5).JPG" />
      <img src="https://gxy-life.com/images/blog/202103/4 (11).JPG" />
      <img src="https://gxy-life.com/images/blog/202103/5 (9).JPG" />
      <img src="https://gxy-life.com/images/blog/202104/3 (3).JPG" />
      <img src="https://gxy-life.com/images/blog/202104/4 (4).JPG" />
      <img src="https://gxy-life.com/images/blog/202101/4 (10).JPG" />
    </div>
  </div>

CSS

  .slider {
      max-width: 500px;
      max-height: 400px;
      position: relative;
      margin: 0 auto 30px;
    }
    .images {
      width: 98%;
      min-height: 326px;
      position: relative;
      margin: 0 auto;
      transition: all 1s ease;
      border-radius: 10px;
      overflow: hidden;
    }
    .images img {
      position: absolute;
      width: 100%;
      top: 0;
      left: 0;
      border-radius: 10px;
    }
    .images img.next {
      z-index: 80;
    }

アニメーション

今回は1例を紹介しますが、アニメーションを変えるだけで、いろいろ表現できます。

  .slider .images img.active {
      animation: slider 3s ease-in-out infinite;
      z-index: 100;
    }
    @keyframes slider {
      0% {
        transform: scale(1.2);  /* 最初少し拡大しておく */
        filter: blur(10px); /* 最初ぼかしておく */
      }
      40% {
        transform: scale(1);  /* もとの大きさに戻す */
        filter: blur(0);  /* ぼかしをなくす */
      }
    }

javascript

  const img = document.querySelectorAll(".slider .images img");
  let index = 1;

  function slider() {
    img.forEach((element) => {  //  最初にクラスactive,nextを削除
      element.classList.remove("next");
      element.classList.remove("active");
    });
    if (index < img.length) {   //  indexが画像枚数より少ない時の処理
      img[index].classList.add("active");
      if (index < img.length - 1) {
        img[index + 1].classList.add("next");
      } else {
        img[0].classList.add("next");
      }
    }
    if (index >= img.length) {  //  indexが画像枚数と一致した時
      index = 0;  //  indexをリセット
      img[0].classList.add("active");  // 画像1枚目にactive
      img[1].classList.add("next");  // 画像2枚目にnext
    }
    index++;  // 処理を終えたらプラス1
  }
  setInterval(slider, 3000);  //  3秒ごとに処理

以上、スライダーの作り方を紹介しました。アニメーションを色々変えて、アレンジしてみてください。

こんな記事も読まれています。

profile

パソコン好きなガオ

コロナ禍によるステイホームを機にプログラミングを学ぶ。パソコンに関してはプロではないが、ちょっと詳しい程度。

パソコン

javascript

カメラ

ブログ