• Skip to primary navigation
  • Skip to main content

Nagashima Laboratory

  • Home
  • Lecture
  • Note
  • Index
  • About

JavaScriptプラグイン(Swiper)

Swiperとは

スライダーを作るためのJavaScriptプラグインです。スライダーは、複数のコンテンツを切り替える機能のことで、スライドショー、カルーセル(循環型のスライダー)とも言われます。

  • 公式サイト:https://swiperjs.com/
  • 動作サンプル:https://ngsm-syr.github.io/javascript_swiper/
  • サンプルコード:https://github.com/ngsm-syr/javascript_swiper

準備

①「JavaScriptを書くための準備」の資料を参考にして、空のHTML、CSS、JavaScriptファイルを作ります。

②フォルダの名前を javascript_swiperに変更します

設置方法

下記に手順を書きますが、実際のコードは公式サイトから確認してください。

①公式サイトにアクセスし、Get Started に移動します。このあとの手順は、Get Started ページの指示に従って進めます。

②Use Swiper from CDN を参照し、CSSとJavaScript のコードをHTMLのhead部分に貼り付けます。このとき、自分でリンクしているCSSやJavaScriptファイルより前に読み込むようにします。

▼index.htmlへの追記 コメントアウト部分に追加

<!-- この部分に css と JavaScriptを読み込みます -->

  <link rel="stylesheet" href="style.css">
  <script src="script.js" defer></script>
</head>

③Add Swiper HTML Layoutを参照し、HTMLファイルに swiper のためのコードを追加します。

▼index.htmlへの追記 コメントアウト部分に追加

<main>

<!-- この部分にタグを追加 -->

</main>

④CSSを追加します。公式サイトでは、.swiper に width と height を設定した例が書かれています。今回は、下記の通り、CSSを追加してください。

▼style.css への追記

* {
  margin: 0;
  padding: 0;
}

html,
body,
main {
  position: relative;
  height: 100%;
}

header {
  position: fixed;
  top: 1rem;
  left: 1rem;
  z-index: 100;
}

footer {
  position: fixed;
  bottom: 1rem;
  right: 1rem;
  z-index: 100;
}

.swiper {
  width: 100%;
  height: 100%;
}

.swiper-slide {
  text-align: center;
  font-size: 2rem;
  display: flex;
  justify-content: center;
  align-items: center;
}

.swiper-slide img {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

⑤Initialize Swiper を参照して、swiperを起動するための、JavaScriptを記述します。

▼script.jsへの追記 コメントアウト部分に追加

// JavaScript
// console.log('Hello world!');

// ここにコードを追加します

console.log の行は、コメントアウトして差し支えありません

【応用】文字の代わりに画像をスライドさせる

.swiper-slideの中に画像を配置すれば、画像をスライドさせることができます。

サンプル画像のダウンロードはこちら。

▼index.htmlへの追記・修正

<div class="swiper-slide"><img src="images/01.png" alt="01"></div>
<div class="swiper-slide"><img src="images/02.png" alt="02"></div>
<div class="swiper-slide"><img src="images/03.png" alt="03"></div>

【応用】スライドの動きを変更する

公式サイトのdemoページには、使用例とサンプルコードが掲載されています。こちらを参考にカスタマイズをしてみてください。

  • 作成例:https://ngsm-syr.github.io/javascript_swiper/
  • コード:https://github.com/ngsm-syr/javascript_swiper/

2024-05-24 (Last Modified: 2024-05-24) Category: 資料 Tags:javascript

Copyright © 2023–2025 · Nagashima Sayuri Laboratory