【jQuery】クロスフェード画像

by tea4two

HTML

<div id="container">
    <ul>
        <li>
            <img src="http://placekitten.com/200/200" alt="" />
        </li>
        <li>
            <img src="http://placekitten.com/g/200/200" alt="" />
        </li>
        <li>
            <img src="http://placekitten.com/200/200" alt="" />
        </li>
        <li>
            <img src="http://placekitten.com/g/200/200" alt="" />
        </li>
        <li>
            <img src="http://dummyimage.com/200x200/000/fff.jpg" alt="" />
        </li>
    </ul>
</div>

CSS

body {
    padding: 0; margin: 0;
}
ul, li {
    list-style: none;
    padding: 0; margin: 0;
}
img {
    vertical-align: bottom;
}

ul {
    position: relative;
}
ul li {
    position: absolute;
}

JavaScript

$(function() {
    
    var _child = $('#container > ul li'),
        _zIndex = 1000,//1コマ目のz-index(一番大きい値になる)
        _childLeng = _child.length,
        _intvl = 2000;//間隔2秒
    
    //初期整列
    for(var i=0; i<_childLeng; i++) {
        _child.eq(i).css({'z-index': _zIndex});
        _zIndex--;
    }
    
    var _num = 0;//フェード用カウンター

    //フェーダー
    function fader() {
        if(_num === _childLeng-1) {
            _child.eq(0).fadeIn(function() {
                _child.css({'display': 'block'});
                _num = 0;//全てのフェードが終わったら戻す
                timer();
            });
        } else {
            _child.eq(_num).fadeOut(function() {
                _num++;
                timer();
            });
        }
    }
    
    //タイマー
    function timer() {
        setTimeout(function(){
            fader();
        },2000);
    }
    //イニシャライズ
    timer();

});