スライドショー(初歩)

JavaScriptで画像のスライドショーを実装する一番初歩的なやりかた。

まずは、画像をクリックすると次の画像に切り替わる単純な仕組みから。

DOM要素の取得などは、とりあえずjQueryを使っている。

[sample01.html]

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>sample01</title>
  <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script type="text/javascript" src="./sample01.js"></script>
  <link rel="stylesheet" href="./css/sample01.css" type="text/css" media="all">
</head>
<body>
  <div id="main">
    <img id="sample-img" onclick="slideshow()" src="images/001.jpg">
  </div>
</body>
</html>

[sample01.css]

#main {
  width: 580px;
  height: auto;
}

#sample-img {
  width: 100%;
  height: auto;
}

[sample01.js]

'use strict';

let path = "./images";
const image_src = new Array(`${path}/001.jpg`,`${path}/002.jpg`,`${path}/003.jpg`,`${path}/004.jpg`,`${path}/005.jpg`);
let num = 0;

function slideshow(){
    if (num == 4) {
        num = 0;
    }
    else {
        num ++;
    }
    $("#sample-img").attr("src", image_src[num]);
}

(DEMO) sample01

世界遺産の画像が./images配下に5つあり、クリックすると順に切り替わる。