Written by Kasumi

【Swiper】自動で無限に横スクロールされるスライダーを実装する方法

Swiperスライダーを使って、自動で無限に横スクロールされるスライダーを実装したい。

本記事ではこのような悩みを解決。

実装方法について解説します。

※本記事ではSwiperプラグインを使います。事前に実装環境で使えるようCDNなどでご用意ください。

無限横スクロールの実装サンプル

See the Pen
Swiper スライド幅を固定する方法
by Kohei (@kouk05)
on CodePen.0

実装サンプルです。

横方向に無限スクロールされるスライダーが実装されています。

実装手順は以下の通りです。

HTMLを用意

<!-- Swiper-->
<div class="swiper">
  <div class="swiper-wrapper">
    <!-- スライド -->
    <div class="swiper-slide">
      <img src="https://placehold.jp/aa0000/ffffff/150x150.png" alt=""> 
      </div>
    <div class="swiper-slide">
            <img src="https://placehold.jp/00aa00/ffffff/150x150.png" alt=""> 
    </div>
    <div class="swiper-slide">
            <img src="https://placehold.jp/aaaa00/ffffff/150x150.png" alt="">
    </div>
        <div class="swiper-slide">
            <img src="https://placehold.jp/aa00aa/ffffff/150x150.png" alt="">
    </div>
        <div class="swiper-slide">
            <img src="https://placehold.jp/00aaaa/ffffff/150x150.png" alt="">
    </div>
</div>

まず最初にSwiperスライダーの実装HTMLを用意します。

Swiper公式にもあるように通常のSwiperを実装するためのHTMLで大丈夫です。

CSSで等倍処理

/* 等倍 */
.swiper-wrapper {
  -webkit-transition-timing-function: linear;
  -o-transition-timing-function: linear;
  transition-timing-function: linear; 
}

次にCSSでswiper-wrapper要素に対して上記transition-timing-functionプロパティを指定します。

値にlinearを指定する事で等倍にします。

JSでSwiperの実行関数を定義

// 横スクロール
  const swiper = new Swiper(".swiper", {
    loop: true, // ループ
    slidesPerView: 3, // 一画面に表示する枚数
    speed: 6000, // ループの時間
    allowTouchMove: false, // スワイプ無効
    autoplay: {
      delay: 0, // 途切れなくループ
    },
  });

最後にSwiperの実行関数を定義します。

上記プロパティを指定する事で横方向に無限スクロールされるスライダーの完成です。

speed、slidesPerViewプロパティの値を調整。

任意で無限スクロールのスピード、一画面に表示するスライドの数を設定してみましょう。

まとめ

Swiperで自動無限横スクロールされるスライダーを実装する方法について紹介しました。

以上で解説を終わります。

目次

関連記事

Swiper

【swiper】スライド時にズーム機能をつけれるスライダーを実装【簡単】

更新日:2022.11.25
3053
Swiper

Swiperでサムネイル固定のスライダーを実装する方法

更新日:2022.11.25
5650
Swiper

左右に見え隠れするスライダーを高さ固定で実装する方法【swiperを使用】

更新日:2022.11.25
4564
Swiper

【Swiper】指定したindex(インデックス)番号のスライドがアクティブの時、処理を実行する方法

2023.11.21
736