基于jQuery的輪播插件

function SwitchImg(boxId,imgClass){
    $('body').css({overflowX:'hidden'});
    var box = $("#"+boxId);
    var w = box.width();
    var boxHeight = box.height();
    var images = $('.'+imgClass);
    var count = images.length;
    var wrap = $("<div>").css({
        position:'relative',
    }).height(boxHeight);

    var train = $("<div>").css({
        position:'absolute',
        left:0,
        width:(count*w)+"px",
        height:boxHeight+"px"
    });

    images.css({
        height:boxHeight+"px",
        width:w+"px",
        float:'left',
        position:'relative'
    });

    wrap.append(train.append(images)).appendTo(box);

    var nowIndex = 0;

    this.left = function(){
        if(nowIndex < count - 1){
            train.stop().animate({
                left:(-(nowIndex+1)*w)+"px"
            },function(){
                nowIndex ++;
            });
        }else if(nowIndex == count - 1){
            var first = images.eq(0).clone().css({
                position:"absolute",
                width:w+"px",
                height:boxHeight+"px",
                left:w+"px",
            }).appendTo(wrap);

            train.stop().animate({
                left:(-(nowIndex+1)*w)+"px"
            });

            first.animate({
                left:0
            },function(){
                first.remove();
                train.css({left:0});
                nowIndex = 0;
            });
        }
    };

    this.right = function(){
        if(nowIndex > 0){
            train.stop().animate({
                left:(1 - nowIndex)*w+"px"
            },function(){
                nowIndex --;
            });
        }else if(nowIndex == 0){
            var last = images.eq(count - 1).clone().css({
                position:"absolute",
                width:w+"px",
                height:boxHeight+"px",
                left:-w+"px",
            }).appendTo(wrap);

            train.stop().animate({
                left:w+"px"
            });

            last.animate({
                left:0
            },function(){
                last.remove();
                train.css({left:(1 - count)*w+"px"});
                nowIndex = count - 1;
            });
        }
    };

    var interval;

    this.start = function(){
        var that = this;
        interval = setInterval(function(){
            that.left();
        },2000);
    };

    this.clear = function(){
        clearInterval(interval);
    };
}

用法:

var img = new SwitchImg("ppt","large");

img.start();

$("#ppt-arrow-left").click(function(){
    img.clear();
    img.left();
});

$("#ppt-arrow-right").click(function(){
    img.clear();
    img.right();
});
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容