GHWEB06.GRASSHOPPER

jQueryでスライドショーを作成

  • Category:Web関連
  • Web関連の備忘録

slideサイトのトップページでよくみかけるスライドショーをjQueryで作成。プラグインを使わないメリットはライセンスを気にしなくて良い所と自由にカスタマイズが出来る所です。

スクリプトとサンプル

$(function(){
var imgSize = 400;
var kazu = $('#thumbslist li').length;
$('#thumbslist li:last').prependTo('#thumbsbox ul');
$('#thumbsbox').css('margin-left',-imgSize+'px').css('width',(imgSize*kazu)+'px');
setInterval(function(){
$('#thumbsbox').animate({
marginLeft:parseInt($('#thumbsbox').css('margin-left'))-imgSize+'px' 
},'midle','swing',
function(){
$('#thumbsbox').css('margin-left',-imgSize+'px'); 
$('#thumbslist li:first').appendTo('#thumbslist');
});
},3000);
});

サンプル

スクリプトの処理内容

$(function(){

/* 画像のサイズを変数 imgSize に代入 */
var imgSize = 400;

/*
#thumbslist li の数を変数 kazu に代入
サンプルでは 5 です。
*/
var kazu = $('#thumbslist li').length;

/* $( A ).prependTo( B ) で B に A の要素を追加 */
$('#thumbslist li:last').prependTo('#thumbsbox ul');

/*
#thumbsbox の margin-left値を指定

#thumbsbox の width 値を指定。
サンプルの場合、400×5 で 2000px ですので
css('width',2000+'px') と書いてもOKです。
その場合、imgSize kazu の指定は削除。

それをしていないのは、スライドの数に増減があった場合、
再指定が考えられますので ('width',(imgSize*kazu)+'px') としています。
*/
$('#thumbsbox').css('margin-left',-imgSize+'px').css('width',(imgSize*kazu)+'px');

/* setInterval()でfunction(){…}の処理を一定間隔で繰替えし */
setInterval(function(){

/*
#thumbsboxにanimateを指定
*/
$('#thumbsbox').animate({

/* 
parseIntで $('#thumbsbox').css('margin-left') の値を
文字列から数値に変換し imgSize 分を減算。
*/
marginLeft:parseInt($('#thumbsbox').css('margin-left'))-imgSize+'px' 

/* animate のスピードと動きを指定 */
},'midle','swing',

/* function 以降は animate 後の処理 */
function(){

/* #thumbsbox の margin-left値を指定 */
$('#thumbsbox').css('margin-left',-imgSize+'px');

/* $("A").appendTo("B"); で B に Aの要素を追加 */
$('#thumbslist li:first').appendTo('#thumbslist');
});

/* 繰り返しの時間(ミリ秒)*/
},3000);

});
  • 掲載: