0

サイトで 4 つの画像を循環する必要があります。サイトに別のプラグインを追加したくなかったので、独自の単純なカルーセル (以下の html、css、および js) を作成しました。

私の質問は、このコードを見るだけで、それを行うための明らかに簡単な/より良い方法はありますか?

html:

<section id="carousel">
    <img src="images/image_00.jpg" width="202" height="162" />
</section>

CSS:

#carousel{text-align:center;position:relative;}
#carousel img{top:0;left:0;z-index:1;position:absolute;}

js:

function carousel(el, base_url, images, i){
    if (i == images.length ) i = 0;
    var el2 = $(el).clone();
    $(el).css('z-index', '1');
    el2.css('z-index', '0');
    el2.attr('src', base_url + images[i]);
    $(el).after(el2);
    $(el).fadeOut('slow', function(){
        $(this).remove();
    });
    i++;
    var func = function(){return carousel(el, base_url, images, i);};
    window.timer = setTimeout(func, 4000);
}
$(document).ready(function(){
    carousel('#carousel img:first',
             'images/', 
             ['image_00.jpg',
              'image_01.jpg',
              'image_02.jpg',
              'image_03.jpg'], 
             0);
});
4

1 に答える 1

0

これが私の最適化されたバージョンです...

HTML

<!-- "section" is not valid HTML -->
<div id="carousel">
         <img src="images/01.jpg" width="202" height="162" />
</div>

CSS

/* Same as before */
#carousel{text-align:center;position:relative;}
#carousel img{top:0;left:0;z-index:1;position:absolute;}

Javascript

function carousel(el, base, images, i){
    //Made the "i" parameter optional
    if (i == images.length || i == null) i = 0;
    //Put the variables in a better order
    var el2 = $(el).clone();
    el2.attr('src', base + images[i]);
    el2.css('z-index', '0');
    $(el).css('z-index', '1');
    $(el).after(el2);
    //One line...
    $(el).fadeOut('slow', function(){$(this).remove();});
    i++;
    //The function doesn't have to be in a variable
    window.timer = setTimeout(function(){return carousel(el, base, images, i);}, 4000);
}

$(function($){
    //Didn't include "i" variable
    carousel('#carousel img:first',
             'images/', 
             ['01.jpg',
              '02.jpg',
              '03.jpg',
              '04.jpg']);
});
于 2010-08-21T20:00:28.227 に答える