@ JavaScript

Carousel:カルーセル

jQuery のプラグインとしても数多くリリースされている Carousel(カルーセルスライダー)を javaScript のシンプルなソースコードで実装してみます。

carousel.html

<!DOCTYPE html>
<html lang="ja">

<head>
<meta charset="utf-8">
<title>sample</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/sanitize.css">
<style>
html {
  overflow: hidden;
}
.slidein {
  animation: slidein 2s;
}
@keyframes slidein {
  from {
    margin-left: 100%;
  }
  to {
    margin-left: 0%;
  }
}
.slideout {
  animation: slideout 2s;
}
@keyframes slideout {
  from {
    margin-left: 0%;
  }
  to {
    margin-left: -100%;
  }
}
#carousel {
  width: 100%;
}
img {
  width: 100%;
  min-width: 100%;
}
</style>
</head>

<body>
<div id="carousel">
  <img src="images/slide01.jpg" id="slide1" class="images" style="position:absolute;">
  <img src="images/slide02.jpg" id="slide2" class="images" style="position:absolute;">
</div>
<script>
var n = 0;
var slideImg = new Array;
slideImg[n++] = "images/slide01.jpg";
slideImg[n++] = "images/slide02.jpg";
slideImg[n++] = "images/slide03.jpg";
slideImg[n++] = "images/slide04.jpg";
var currentImg = -1;
var flg = 0;

function slide() {
  currentImg = (currentImg < slideImg.length - 1) ? currentImg + 1 : 0;
  nextImg = (currentImg < slideImg.length - 1) ? currentImg + 1 : 0;
  flg = (flg == 0) ? 1 : 0;

  if (flg == 0) {
    document.getElementById("slide1").src = slideImg[nextImg];
    document.getElementById("slide2").src = slideImg[currentImg];
    document.getElementById("slide1").className = "slidein";
    document.getElementById("slide2").className = "slideout";
    document.getElementById("carousel").appendChild(slide1);
  } else {
    document.getElementById("slide1").src = slideImg[currentImg];
    document.getElementById("slide2").src = slideImg[nextImg];
    document.getElementById("slide1").className = "slideout";
    document.getElementById("slide2").className = "slidein";
    document.getElementById("carousel").appendChild(slide2);
  }

  setTimeout("slide()", 5000);
}

window.onload = slide;
</script>
</body>

</html>

demo