美文网首页
基于jQuery的轮播插件

基于jQuery的轮播插件

作者: EdisonDong | 来源:发表于2016-11-10 15:38 被阅读0次
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();
});

相关文章

网友评论

      本文标题:基于jQuery的轮播插件

      本文链接:https://www.haomeiwen.com/subject/ourxpttx.html