プラグインに頼らず自力でjQueryのスライドショーを作る方法(はじめてのスライドショー作成編)
2013/06/21
【ステップ3】スライドインタイプのスライドショーにしてみる
<style type="text/css">;
#slideShow img{
/* 全てを透明にして、画像を重ねる */
opacity: 0;
position: absolute;
}
#slideShow .img1{
/* 1枚目の画像だけ表示 */
opacity: 1;
}
</style>
CSSは変更はありません。
<script type="text/javascript">;
var flg=2; //「2枚目に切り替え」からスタートするため、flg に 2 をセット
$(function(){
setInterval(function() {
switch(flg){
case 1:
//1枚目に切り替え
$(".img3").animate({opacity:0});
$(".img1").css({"margin-left":"250px"});
$(".img1").animate({
opacity:1,
"margin-left":"0px"
},"slow");
break;
case 2:
//2枚目に切り替え
$(".img1").animate({opacity:0});
$(".img2").css({"margin-left":"250px"});
$(".img2").animate({
opacity:1,
"margin-left":"0px"
},"slow");
break;
case 3:
//3枚目に切り替え
$(".img2").animate({opacity:0});
$(".img3").css({"margin-left":"250px"});
$(".img3").animate({
opacity:1,
"margin-left":"0px"
},"slow");
break;
}
$("#debug").text(flg); //デバッグ用(ここは削除します)
flg++;
if(flg>3){
flg=1; //flg が 3 を越えたら 1 に戻す
}
}, 3000); //setInterval() で 3秒間隔で実行
});
</script>
フェードインの処理を行う前の非表示の段階で、marginを使って右にずらしておきます。その後、opacityを1するのと同時に、marginの値を0(ゼロ)pxにすることで右から左にスライドしていきます。
<p id="debug">;debug</p>; <div id="slideShow"> <img src="img1.jpg" class="img1"> <img src="img2.jpg" class="img2"> <img src="img3.jpg" class="img3"> </div>
HTMLも変更はありません。
jQueryの本体を読み込むのを忘れないように!

