簡単にスライドを作れるJSライブラリ「Swiper.js」を紹介

WEB制作

Swiper.jsとは

簡単にスライダーを実装することができるJavaScriptのライブラリです。いろんなパターンのスライダーにも対応できるのですごくいいと思います。

使い方

スライダーを実装したいページのHTMLに以下を追加することで、CDNからライブラリを読み込むことができます。

<link rel="stylesheet" href="https://unpkg.com/swiper@7/swiper-bundle.min.css"/>
<script src="https://unpkg.com/swiper@7/swiper-bundle.min.js"></script>

※最新のものは以下のこちらのページをご確認ください
https://swiperjs.com/get-started#use-swiper-from-cdn

使用例

以下のソースコードをファイルにコピーして利用してください。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/style.css" />
    <link rel="stylesheet" href="https://unpkg.com/swiper@7/swiper-bundle.min.css" />
    <script src="https://unpkg.com/swiper@7/swiper-bundle.min.js"></script>
</head>
<body>
<div class="container">
    <div class="swiper-container">
        <div class="swiper-wrapper">
            <div class="swiper-slide">1枚目</div>
            <div class="swiper-slide">2枚目</div>
            <div class="swiper-slide">3枚目</div>
            <div class="swiper-slide">4枚目</div>
        </div>
        <div class="swiper-button-prev"></div>
        <div class="swiper-button-next"></div>
        <div class="swiper-pagination"></div>
    </div>
</div>

<script>
    var mySwiper = new Swiper('.swiper-container', {
            autoHeight: true,
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev'
            },
            pagination: {
                el: '.swiper-pagination',
                type: 'bullets',
                clickable: true
            }
        });
</script>
</body>
</html>
.container {
    width: 600px;
    height: 300px;
    overflow: hidden;
    position: relative;
}

.swiper-wrapper {
    box-sizing: border-box;
    width: 100%;
    height: 100%;
}

.swiper-slide {
    box-sizing: border-box;
    color: #ffffff;
    width: 100%;
    height: 100%;
    text-align: center;
    line-height: 300px;
}

.swiper-slide:nth-child(4n+1) {
    background-color: #ee2727;
}

.swiper-slide:nth-child(4n+2) {
    background-color: #3243e1;
}

.swiper-slide:nth-child(4n+3) {
    background-color: #fffb00;
}

.swiper-slide:nth-child(4n+4) {
    background-color: #3cff00;
}