【jQuery】簡単シンプルなスライドショー

jQueryでプラグインなど使わず簡単クロスフェードのスライドショーを実現する 参考:http://jonraasch.com/blog/a-simple-jquery-slideshow

by tea4two

HTML

<!--この例では4番目を初期に指定-->
<ul id="slideShow">
    <li id="no1"><a href="">abcd</a></li>
    <li id="no2"><a href="">efgh</a></li>
    <li id="no3"><a href="">ijkl</a></li>
    <li id="no4" class="active"><a href="">mnso</a></li>
</ul>

CSS

ul {
    position: relative;
    width: 300px;
    height: 150px;
}
ul li {
    width: 300px;
    height: 150px;
    position: absolute;
    left: 0;
    top: 0;
}
ul li.active { z-index: 5; }
ul li.last-active { z-index: 4; }
#no1 { background: #5dd; }
#no2 { background: #d88; }
#no3 { background: #e55; }
#no4 { background: #e9d; }

JavaScript

var timeout = 3000;//ホールドする時間(ミリ秒)
var speed = 600;//切り替えのスピード(ミリ秒)

function slideSwitch(){
    var $active = $('#slideShow li.active');
    if ( $active.length == 0 ) $active = $('#slideShow li:last');
    var $next =  $active.next().length ? $active.next() : $('#slideShow li:first');

    $active.addClass('last-active');
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, speed, function() {
            $active.removeClass('active last-active');
        });
}

$(function() {
    setInterval(function(){
        slideSwitch();
    }, timeout);
});