jQueryで作るシンプルなスライドショー

HTMLの部分
目標はとにかくキレイなコードにすること。

<div id="slideshow">
 <img src="images/image01.jpg" alt="" class="active" />
 <img src="images/image02.jpg" alt="" />
 <img src="images/image03.jpg" alt="" />
</div>

CSSの部分
activeに指定した画像が一番上にくるようにCSSを設定します。
画像がきれいに重なるようにdevの高さを指定しています。
3つの異なるz-indexを指定しているのに気づかれるでしょうか?
後でjQueryでこれらを操作します。

#slideshow {
position:relative;
height:200px;
}
#slideshow IMG {
position:absolute;
top:0;
left:0;
z-index:8;
}
#slideshow IMG.active {
z-index:10;
}
#slideshow IMG.last-active {
z-index:9;
}

javascriptの部分

スライドショーアニメーションのために、各写真を定期的に入れ替える必要があります。では、アクティブになっているイメージの上に新しいイメージを表示する部分から書き始めましょう。

<script type="text/javascript" src="js/vendor/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
function slideSwitch() {
var $active = $('#slideshow IMG.active');
        var $next = $active.next();
$active.addClass('active');
$active.removeClass('active');
}
$(function() {
setInterval( "slideSwitch()", 5000 );
});
</script>

ここで5秒ごとにsildeSwitch()を呼び出すようjavascriptを設定しています。
そしてslideSwitch()はCSSのactiveを次に呼び出す画像に適用して一番上に持ってきます。

次に、画像の重なりを加えます。
こういうギャラリーにはフェードイン・フェードアウトは重要ですね。

<script type="text/javascript" src="js/vendor/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
function slideSwitch() {
var $active = $('#slideshow IMG.active');
        var $next = $active.next();
$active.addClass('last-active');
$next.css({opacity: 0.0})
.addClass('active')
.animate({opacity: 1.0}, 1000, function() {
$active.removeClass('active last-active');
});
}
$(function() {
setInterval( "slideSwitch()", 5000 );
});
</script>

最初に設定した’last-active’クラスを適用します。
‘last-active’はスタイルシートの中で’active’のつぎにきますのでz-indexが9のほうが上にきます。そして一番上の画像は一段下がります。
次に新しい画像のopacityを0にしてanimate()functionをつかってフェードします。
最後に、前の画像のz-indexを消去するためにcallbackを使います。

これでこのスライドショーは大体動いていますが、まず、back-endの負担を軽くするためにデフォルトのactiveイメージを設定します。
あと、ループするようにします。

<script type="text/javascript" src="js/vendor/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
function slideSwitch() {
var $active = $('#slideshow IMG.active');
if ( $active.length == 0 ) $active = $('#slideshow IMG:last')
var $next = $active.next().length ? $active.next()
: $('#slideshow IMG:first');
$active.addClass('last-active');
$next.css({opacity: 0.0})
.addClass('active')
.animate({opacity: 1.0}, 1000, function() {
$active.removeClass('active last-active');
});
}
$(function() {
setInterval( "slideSwitch()", 5000 );
});
</script>

参考サイト:
http://jonraasch.com/blog/a-simple-jquery-slideshow

コメント

タイトルとURLをコピーしました