作ったものの仕組みが分からず困っています。
スライドショーを作りました。
5つの画像(ここでは背景色を変えただけ)を横に並べて、左に動かすことでスライドショーのように見せようとしました。
(codepenを見ていただいたほうが伝わりやすいかと思います:https://codepen.io/hayamine01/pen/Lwgxvp)
5つ目のスライドまできたら、1枚目に戻るようになっています。
以下のコードを書き、とりあえず動きました。
しかし、なぜそうなるのか分からない箇所があります。
HTML
1<div class="slide-show"> 2 <div class="slides"> 3 <a href="#" class="slide item1"></a> 4 <a href="#" class="slide item2"></a> 5 <a href="#" class="slide item3"></a> 6 <a href="#" class="slide item4"></a> 7 <a href="#" class="slide item5"></a> 8 </div> 9</div>
CSS
1 2.slide-show { 3 position: relative; 4 width: 300px; 5 height: 200px; 6 margin: 60px; 7 overflow: hidden; 8} 9 10.slides { 11 position: absolute; 12} 13 14.slide { 15 position: absolute; 16 top: 0; 17 width: 300px; 18 height: 200px; 19} 20 21.item1 { 22 background: skyblue; 23} 24.item2 { 25 background: pink; 26} 27.item3 { 28 background: rgb(117, 197, 117); 29} 30.item4 { 31 background: rgb(214, 132, 214); 32} 33.item5 { 34 background: rgb(245, 187, 79); 35}
jQuery
1$(function () { 2 $('.slide-show').each(function () { 3 var $slideAll = $('.slide-show').find('.slides'), 4 $slides = $slideAll.find('.slide'), 5 lideCount = $slideAll.length, 6 currentIndex = 0; 7 8 //スライドを横一列に並べる 9 $slides.each(function (index) { 10 $(this).css({ 11 left: 300 * index 12 }); 13 }); 14 15 function moveSlide (i) { //スライド全てを同時に横に動かす 16 $slideAll.animate({ 17 left: -300 * i //左に-300px * iずつ動かす 18 },500) 19 } 20 21 function loop () { 22 setInterval (function () { 23 moveSlide(currentIndex); 24 currentIndex = i++; //次のスライドに移るためにcurrentIndexを更新する 25 26 if (currentIndex === 5) { //もし最後のスライドまでいったら 27 currentIndex = 0; //最初のスライドまで戻る 28 } 29 },3000); 30 } 31 moveSlide(currentIndex); 32 loop(); 33 }); 34});
jQueryの下から9行目のif文内に (currentIndex === 5) と書いています。
スライドは0から始まると思っていたので、なぜ5枚あるスライドの最後を表示するのに5を使うのでしょうか。
はじめは (curretIndex === slideAll.length -1) と書いていたのですが、これでは一切動きませんでした。そこで4を入れてみたところ動き、試しに5にしてみたらすべてを表示できました。
1からスタートしているということなのだと思いますが、イマイチしっくりきません。
なぜスライドの1枚目は0ではなく1となっているのか、
また、なぜ(curretnIndex === slideAll.length -1) ではまったく動かなかったのか、どなたかご教授ください。
回答1件
あなたの回答
tips
プレビュー