jQuery封裝的輪播圖組件(按需加載)

效果圖javascript

slider.htmlcss

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>slider</title>
    <link rel="stylesheet" href="../css/base.css">
    <link rel="stylesheet" href="../css/slider.css">
</head>
<body>
    <div class="slider">
        <div class="slider-img slide-slide">
            <a href="#" class="slider-img-item"><img src="../img/focus-slider/loading.gif" data-src="../img/focus-slider/1.png" class="slider-pic"></a>
            <a href="#" class="slider-img-item"><img src="../img/focus-slider/loading.gif" data-src="../img/focus-slider/2.png" class="slider-pic"></a>
            <a href="#" class="slider-img-item"><img src="../img/focus-slider/loading.gif" data-src="../img/focus-slider/3.png" class="slider-pic"></a>
            <a href="#" class="slider-img-item"><img src="../img/focus-slider/loading.gif" data-src="../img/focus-slider/4.png" class="slider-pic"></a>
        </div>
        <ol class="slider-tip">
            <li class="slider-tip-item text-hidden fl">1</li>
            <li class="slider-tip-item text-hidden fl">2</li>
            <li class="slider-tip-item text-hidden fl">3</li>
            <li class="slider-tip-item text-hidden fl">4</li>
        </ol>
        <a href="javascript:;" class="slider-arrow slider-arrow-left">&lt;</a>
        <a href="javascript:;" class="slider-arrow slider-arrow-right">&gt;</a>
    </div>

    <script src="../js/jquery.js"></script>
    <script src="../js/transition.js"></script>
    <script src="../js/showhide.js"></script>
    <script src="../js/move.js"></script><!-- 滑動模塊 -->
    <script src="../js/slider.js"></script>
    <script>
        var slider=$(".slider");

        //設置全局變量的屬性
        slider.loadedPics={};//用來保存已經加載過的圖片
        slider.loadedPicsNum=0;//已經加載的圖片數量
        slider.totalPicsNum=slider.find(".slider-pic").length;//總共須要加載的圖片數量

        //接收到開始顯示圖片的消息
        slider.on("slider-show",slider.loadFn=function(e,i,elem){
            console.log("開始顯示圖片");
            if(slider.loadedPics[i] !== "loaded"){
                console.log("準備加載圖片"+i);
                slider.trigger("slider-loadPic",[i,elem]);                
            }        
        });

        //綁定開始加載圖片的自定義事件
        slider.on("slider-loadPic",function(e,i,elem){
            //按需加載
            var img=$(elem).find(".slider-pic");//這個img是jQuery對象

            loadImg(img.data("src"),function(url){        
                img.attr("src",url);

                slider.loadedPics[i]="loaded";
                slider.loadedPicsNum++;
                console.log(i+"加載完成");

                if(slider.loadedPicsNum===slider.totalPicsNum){
                    // 所有加載完畢
                    slider.trigger("slider-PicLoaded");
                }
            },function(url){
                img.attr("src","../img/focus-slider/placeholder.png");
                console.log(i+"加載失敗");
            })
        })

        //綁定所有加載完畢的自定義事件
        slider.on("slider-PicLoaded",function(e){
            console.log("全部圖片加載完成");
            //清除事件
            slider.off("slider-show",slider.loadFn);
        })

        function loadImg(url,loadedCall,errorCall){
            var img=new Image();//建立一個<img>標籤,這個是原生的js對象
            //圖片加載失敗時執行回調
            img.onerror=function(){
                //圖片加載完成後執行回調
                if(typeof errorCall==="function") errorCall(url);
            }        
            //圖片加載完成後執行回調
            img.onload=function(){                
                if(typeof loadedCall==="function") loadedCall(url);
            }                    
            //人爲延遲模擬線上加載圖片
            setTimeout(function(){
                img.src=url;//原生js對象能夠使用原生js方法
            },500);
        }

        //傳入自定義參數
        slider.Slider({
            css3:true,
            js:true,
            animation:"slide",
            activeIdx:0,//從哪張開始輪播
            interval:1000//xx毫秒的速度輪播        
        });

    </script>
</body>
</html>

base.css  http://www.javashuo.com/article/p-hddyogwd-by.html
slider.csshtml

    /*showhide*/
    .fadeOut{
        opacity: 0;
        visibility: hidden;
    }
    .slideUpDownCollapse{
        height:0 !important;/*避免由於優先級不夠而沒法生效*/
        padding-top:0 !important;
        padding-bottom:0 !important;
    }
    .slideLeftRightCollapse{
        width:0 !important;/*避免由於優先級不夠而沒法生效*/
        padding-left:0 !important;
        padding-right:0 !important;
    }
    .fl{
        float:left;
    }
    .fr{
        float:right;
    }
    /*提取出過渡樣式,可公用*/
    .transition{
        -webkit-transition:all .5s;
        -moz-transition:all .5s;
        -ms-transition:all .5s;
        -o-transition:all .5s;
        transition:all .5s;
    }
    /*文字隱藏*/
    .text-hidden{
        text-indent:-9999px;
        overflow:hidden;
    }
    .slider{
        width:728px;
        height:504px;
        position: relative;
        overflow:hidden;
    }
    .slider-img{
        width:100%;
        height:100%;
        position: relative;
    }
    /*fade方式*/
    .slide-fade .slider-img-item{
        width:100%;
        height:100%;
        position: absolute;
        top:0;
        left:0;    
        display: none;    
    }
    /*slide方式*/
    .slide-slide .slider-img-item{
        width:100%;
        height:100%;
        position: absolute;
        top:0;
        left:100%;        
    }
    .slider-tip{
        position: absolute;
        height:12px;
        width:78px;
        bottom:24px;
        left:50%;
        margin-left:-36px;
    }
    .slider-tip-item{        
        width:8px;
        height:8px;
        border:2px solid #e4e8eb;
        background-color: #313a43;
        margin-right:10px;
        border-radius:50%;
    }
    .slider-tip-item-active{
        background-color:#e4e8eb;
        border:2px solid #313a43;
    }
    .slider-tip-item:last-child{
        margin-right:0;
    }
    .slider-arrow{
        display: none;
        position: absolute;
        width:30px;
        height:40px;
        line-height:40px;
        top:50%;
        margin-top:-20px;
        background-color:rgba(0,0,0,.5);
        color:#e4e8eb;
        text-align: center;
        font-size:20px;
        font-family:simsum;
    }
    .slider-arrow-left{
        left:0;
    }
    .slider-arrow-right{
        right:0;
    }

 

transition.js http://www.javashuo.com/article/p-nbnfsgpd-w.html
showhide.js http://www.javashuo.com/article/p-cgnrmqkl-h.html
move.js http://www.javashuo.com/article/p-fdecvwhv-h.html
slider.js java

(function($){
    'use strict';//使用嚴格模式

    //構造函數形式
    function Slider(elem,options){
        //保存到this中才能公用
        this.elem=elem;
        this.picBox=this.elem.find(".slider-img");
        this.options=options;

        this.pics=this.elem.find(".slider-img-item");
        this.tips=this.elem.find(".slider-tip-item");
        this.arrows=this.elem.find(".slider-arrow");

        this.size=this.pics.length;
        this.curIdx=this._getIdx(this.options.activeIdx);
        
        this._init();//初始化,下劃線開頭一般約定爲僅供內部使用
    }
    //默認參數
    Slider.defaults={
        css3:false,
        js:false,
        animation:"fade",
        activeIdx:0,//從哪張開始輪播
        interval:0//默認沒有自動輪播
    };
    //初始化
    Slider.prototype._init=function(){
        var self=this;

        //初始化時觸發事件,傳入參數爲當前索引,以及當前的圖片
        this.elem.trigger("slider-show",[this.curIdx,this.pics[this.curIdx]]);

        //init show 顯示指定圓點
        this.tips.removeClass("slider-tip-item-active");
        this.tips.eq(this.curIdx).addClass("slider-tip-item-active");

        //指定動畫方式 to
        if(this.options.animation==="slide"){
            //slide
            this.picBox.addClass("slide-slide");
            this.pics.eq(this.curIdx).css("left",0);            

            //slide 模塊  send message
            this.pics.on("move moved",function(e){
                var index=self.pics.index(this);//獲取當前觸發事件的幻燈片的索引

                if(e.type==="move"){
                    //move 開始運動
                    if(self.curIdx===index){
                        //這張開始隱藏
                        self.elem.trigger("slider-hide",[index,this]);
                    }else{
                        //這張開始顯示
                        self.elem.trigger("slider-show",[index,this]);
                    }
                }else{
                    //moved 結束運動
                    if(self.curIdx===index){//此時已經操做了self.curIdx=index; 所以狀況須要相反
                        //這張開始隱藏
                        self.elem.trigger("slider-shown",[index,this]);
                    }else{
                        //這張開始顯示
                        self.elem.trigger("slider-hidden",[index,this]);
                    }
                }
            })

            //move init控制幻燈片的顯示隱藏
            this.pics.move(this.options);
            this.to=this._slide;

            this.picWidth=this.pics.eq(0).width();
            this.transitionCls=this.pics.eq(0).hasClass("transition")?"transition":"";
        
        }else{    
            //fade        
            this.picBox.addClass("slide-fade");
            //顯示指定圖片
            this.pics.eq(this.curIdx).show();

            //fade 模塊 發送消息(調用showhide模塊的是幻燈片元素,所以發送接收消息的也是幻燈片元素)
            this.pics.on("show shown hide hidden",function(e){
                self.pics.trigger("slider-"+e.type,[self.pics.index(this),this]);
                //返回的數組包含當前圖片的索引+觸發事件的對象
            })

            //showHide init控制幻燈片的滑動
            this.pics.showHide(this.options);
            this.to=this._fade;
        }

        //鼠標移入顯示左右箭頭
        this.elem.hover(function(){
            self.arrows.show();
        },function(){
            self.arrows.hide();
        }).on("click",".slider-arrow-left",function(){//左箭頭,圖片left爲正
            //事件代理
            self.to(self._getIdx(self.curIdx-1),1);//第二個參數表明滑動時的方向
        }).on("click",".slider-arrow-right",function(){//右箭頭,圖片left爲負
            self.to(self._getIdx(self.curIdx+1),-1);
        }).on("click",".slider-tip-item",function(){
            self.to(self._getIdx(self.tips.index(this)));
            //self.tips.index(this)是當前點擊的圓點的索引
        });

        //auto 
        if(this.options.interval && !isNaN(Number(this.options.interval))){
            //鼠標移入時暫停自動切換
            this.elem.hover($.proxy(this.pause,this),$.proxy(this.auto,this));

            this.auto();
        }

    };
    //獲取合理的索引
    Slider.prototype._getIdx=function(index){
        if(isNaN(Number(index))) return 0;
        if(Number(index)<0) return this.size-1;
        if(Number(index)>this.size-1) return 0;
        return index;
    }
    //激活小圓點
    Slider.prototype._activateTips=function(index){
        this.tips.eq(this.curIdx).removeClass("slider-tip-item-active");
        this.tips.eq(index).addClass("slider-tip-item-active");
    }
    //淡入淡出方式
    Slider.prototype._fade=function(index){
        if(this.curIdx===index) return;//點擊當前索引再也不切換

        this.pics.eq(this.curIdx).showHide("hide");
        this.pics.eq(index).showHide("show");

        this._activateTips(index);

        this.curIdx=index;
        
    }
    //滑動方式
    Slider.prototype._slide=function(index,direction){
        var self=this;
        if(this.curIdx===index) return;//點擊當前索引再也不切換

        //肯定滑入滑出方向
        if(!direction){
            //click tips
            if(this.curIdx>index){
                direction=1;//向右,left爲正
            }else if(this.curIdx<index){
                direction=-1;//向左,left爲負
            }
        }

        //設置指定滑入幻燈片的初始位置
        this.pics.eq(index).removeClass(this.transitionCls).css("left",-1*direction*this.picWidth);
        
        //當前幻燈片滑出可視區域,指定幻燈片滑入可視區域
        setTimeout(function(){
            self.pics.eq(self.curIdx).move("x",direction*self.picWidth);//當前的滑出可視區
            self.pics.eq(index).addClass(self.transitionCls).move("x",0);//指定圖片滑入,若是是css3,加入剛纔被移除的transition
            self.curIdx=index;
        },20)
        
        //激活tips
        this._activateTips(index);    
        
    }
    //自動
    Slider.prototype.auto=function(){
        var self=this;
        this.timer=setInterval(function(){
            self.to(self._getIdx(self.curIdx+1),-1);
        },self.options.interval);        
    }
    //中止
    Slider.prototype.pause=function(){
        clearInterval(this.timer);    
    }

    //插件形式
    $.fn.extend({
        Slider:function(opt){
            //return this能夠返回對象,方便連寫
            return this.each(function(){
                var ui=$(this);
                var slider=ui.data("slider");
                //opt是參數對象
                var options=$.extend({},Slider.defaults,ui.data(),typeof opt==="object"&&opt);
                
                //單例:一個DOM元素對應一個實例,若是已經存在則不須要反覆實例化
                if(!slider){
                    slider=new Slider(ui,options);
                    ui.data("slider",slider);
                }
                
                //opt是show或者hide
                if(typeof slider[opt]==="function"){
                    Slider[opt]();
                }
            });
        }
    });

})(jQuery);
//爲了防止$符發生衝突,將jQuery做爲參數傳入,則$符做爲內部變量,不會發生衝突

注意:使用trigger的自定義事件時,觸發事件的元素,和綁定事件的元素,必須相同。jquery

相關文章
相關標籤/搜索