$(document).ready(function (){ //kv_slider var kvSlide = function ($element) { //変数宣言 var $children = $element.children(), current = 0, time = 4000; //切り替えの早さ //1番目の要素に、current追加 $children.eq(current).addClass('current'); //順番に、current追加(current += 1)。子要素($children)の数と、current - 1 の数が等しくなったら、currentは0に戻る var interval = time; // initial condition var run = setInterval(request , interval); // start setInterval as "run" function request() { //繰返す処理 $children.eq(current).removeClass('current'); current = current === $children.length - 1 ? 0 : current += 1; $children.eq(current).addClass('current'); clearInterval(run); // stop the setInterval() // 要素の最後だけ interval の間隔を長くする if(current == $children.length - 1 ){ interval = time*1.8; }else{ interval = time; } run = setInterval(request, interval); // start the setInterval() } }; //スライドショーを実行 setTimeout(function() { kvSlide($('#slideshow')); }, 2000); });
<div id="slideshow"> <div class="slide current">Slide1</div> <div class="slide">Slide2</div> <div class="slide">Slide3</div> </div>
#slideshow { position: relative; width: 300px; height: 300px; .slide { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; transition: opacity .75s; &.current { opacity: 1; } //装飾 display: flex; justify-content: center; align-items: center; background: #300; color: #fff; &:nth-child(3n+2) { background: #030; } &:nth-child(3n+3) { background: #003; } } }