DynamicIntervalSlider

by interlife

HTML

<div id="slideshow">
	<div class="slide current">Slide1</div>
	<div class="slide">Slide2</div>
	<div class="slide">Slide3</div>
</div>

CSS

#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; }
	}
}

JavaScript

$(document).ready(function (){

  //kv_slider
  var kvSlide = function ($element) {
    //変数宣言
    var $children = $element.children(),
        current = 0,
        time = 2000; // 基本の切り替え時間(ミリ秒)
    
    // 最終スライドの表示時間を長くする倍率
    var lastSlideDurationRatio = 1.8; 
    
    // 1番目の要素に、currentクラスを追加
    $children.eq(current).addClass('current');
    
    /** スライドを切り替える関数 */
    function request() { 
      // 現在の要素のcurrentクラスを削除
      $children.eq(current).removeClass('current');
      
      // 次のスライドのインデックスを計算(最後の要素であれば 0 に戻す)
      current = (current === $children.length - 1) ? 0 : current + 1;
      
      // 次の要素にcurrentクラスを追加
      $children.eq(current).addClass('current');
      
      // 次の切り替えまでのインターバル時間を設定
      var interval;
      
      // 要素の最後だけ interval の間隔を長くする(設定した倍率を適用)
      if(current === $children.length - 1 ){
        interval = time * lastSlideDurationRatio;
      } else {
        interval = time;
      }
      
      // 指定したインターバル後に再度 request 関数を実行
      setTimeout(request, interval);
    }
    
    // スライドショーの開始(最初のスライド表示後、基本の時間(time)が経過してから request() を実行)
    setTimeout(request, time);
  };

  // スライドショーを実行(2000ms遅延)
  setTimeout(function() {
    kvSlide($('#slideshow')); 
  }, 2000);

});