首頁  >  文章  >  web前端  >  javascript中的輪播圖插件化的封裝範例

javascript中的輪播圖插件化的封裝範例

黄舟
黄舟原創
2017-07-17 16:16:341200瀏覽

本文實例為大家分享了js輪播圖的外掛程式封裝程式碼,供大家參考,具體內容如下

具體程式碼如下:

~function(){
  function AutoBanner(curEleId,ajaxURL,interval){
    //把之前存储获取元素的变量都作为当前实例的私有属性
    this.banner = document.getElementById(curEleId);
    this.bannerInner = utils.firstChild(this.banner);
    this.bannerTip = utils.children(this.banner,"ul")[0];
    this.bannerLink = utils.children(this.banner,'a');
    this.bannerLeft = this.bannerLink[0];
    this.bannerRight = this.bannerLink[1];
    this.pList = this.bannerInner.getElementsByTagName('p');
    this.imgList = this.bannerInner.getElementsByTagName('img');
    this.oLis = this.bannerTip.getElementsByTagName('li');

    //之前的全局变量也应该变为自己的私有属性
    this.jsonData = null;
    this.interval = interval || 3000;
    this.autoTimer = null;
    this.step = 0;
    this.ajaxURL = ajaxURL;
    //返回当前实例
    return this.init();
  }

  AutoBanner.prototype = {
    constructor:AutoBanner,
    //Ajax请求数据
    getData:function(){
      var _this = this;
      var xhr = new XMLHttpRequest;
      xhr.open("get",this.ajaxURL + "?_="+Math.random(),false);
      xhr.onreadystatechange = function(){
        if(xhr.readyState ===4 && /^2\d{2}$/.test(xhr.status)){
          _this.jsonData = utils.formatJSON(xhr.responseText)
        }
      }
      xhr.send(null)
    },
    //实现数据绑定
    bindData:function(){
      var str = "",str2 = "";
      if(this.jsonData){
        for(var i = 0,len=this.jsonData.length;i<len;i++){
          var curData = this.jsonData[i];
          str+=&#39;<p><img src="" alt="" trueImg="&#39;+curData[&#39;img&#39;]+&#39;"></p>&#39;;
          i===0?str2+="<li class=&#39;bg&#39;></li>":str2+="<li></li>"
        }
      }
      this.bannerInner.innerHTMl = str;
      this.bannerTip.innerHTML = str2;
    },
    //延迟加载
    lazyImg:function(){
      var _this = this;
      for(var i = 0,len = this.imgList.length;i<len;i++){
        ~function(i){
          var curImg = _this.imgList[i];
          var oImg = new Image;
          oImg.src = curImg.getAttribute(&#39;trueImg&#39;);
          oImg.onload = function(){
            curImg.src = this.src;
            curImg.style.display = block;
            //只对第一张处理
            if(i===0){
              var curp = curImg.parentNode;
              curp.style.zIndex = 1;
              myAnimate(curp,{opacity:1},200);
            }
            oImg = null;
          }
        }(i)
      }
    },
    //自动轮播
    autoMove:function(){
      if(this.step === this.jsonData.length-1){
        this.step = -1
      }
      this.step++;
      this.setBanner();
    },
    //切换效果和焦点对齐
    setBanner:function(){
      for(var i = 0,len = this.pList.length;i<len;i++){
        var curp = this.pList[i];
        if(i===this.step){
          utils.css(curp,"zIndex",1)
          //2、让当前的透明度从0变为1,当动画结束,我们需要让其他的p的透明度的值直接变为0
          myAnimate(curp,{opacity:1},200,function(){
            var curpSib = utils.siblings(this);
            for(var k = 0,len = curpSib.length;k<len;k++){
              utils.css(curpSib[k],&#39;opacity&#39;,0)
            }

          })
          continue
        }
        utils.css(curp,"zIndex",0)
      }
      //实现焦点对其
      for(i = 0,len = this.oLis.length;i<len;i++){
        var curLi = this.oLis[i];
        i === this.step?utils.addClass(curLi,"bg"):utils.removeClass(curLi,"bg");
      }
    },
    //控制自动轮播
    mouseEvent:function(){
      var _this = this;
      this.banner.onmouseover = function(){
        window.clearInterval(_this.autoTimer);
        _this.bannerLeft.style.display = _this.bannerRight.style.display = "block"

      }
      this.banner.onmouseout = function(){
        _this.autoTimer = window.setInterval(function(){
          _this.autoMove.call(_this)
        },_this.interval);
        _this.bannerLeft.style.display = _this.bannerRight.style.display = "none"
      }
    },
    //实现焦点切换
    tipEvent:function(){
      var _this = this;
      for(var i = 0,len = this.oLis.length;i<len;i++){
        var curLi = this.oLis[i];
        curLi.index = i;
        curLi.onclick = function(){
          _this.step = this.index;
          _this.setBanner();
        }
      }
    },
    //实现左右切换
    leftRight:function(){
      var _this = this;
      this.bannerRight.onclick = function(){
        _this.autoMove();
      };
      this.bannerLeft.onclick = function(){
        if(_this.step === 0){
          _this.step = _this.jsonData.length;
        }
        _this.step--;
        _this.setBanner();
      }
    },
    //当前插件的唯一入口 命令模式:init相当于指挥室,指挥各军队协同作战
    init:function(){
      var _this = this;
      this.getData();
      this.bindData();
      window.setTimeout(function(){
        _this.lazyImg();
      },500);
      this.autoTimer = window.setInterval(function(){
        _this.autoMove();
      },this.interval);

      this.mouseEvent();
      this.tipEvent();
      this.leftRight();
      return this;
    }

  }

  window.AutoBanner = AutoBanner
}()

//使用
var banner1 = new AutoBanner(&#39;banner&#39;,&#39;json/banner.txt&#39;,1000)

程式碼界的小白,工作上需要多次呼叫左右轉換的輪播圖,我就給封裝了。但是總覺得自己寫的程式碼比較繁瑣。方法比較笨,求大神給簡潔化一下,順便學習。 另外如果預設值是top的話。動畫效果會沒有。

$.fn.zuoyouzhuan = function(options) {
        this.each(function(i, ele) {
            slide(ele, options)
        })
        return this
    }
    var slide = function(ele, options) {
        var des = $.extend({
            fangxiang: &#39;left&#39;,
            duoshaotu: &#39;4&#39;,
            sudu: &#39;3000&#39;
        }, options)
        var $ele = $(ele)
        var $ul = $ele.find(&#39;ul&#39;)
        var $li = $ele.find(&#39;li&#39;)
        var x_width = $ele.find(&#39;li&#39;).width()
        var y_height = $ele.find(&#39;li&#39;).height()
        var num = $ele.find(&#39;li&#39;).length;
        if(des.fangxiang == "top") {
            var topmar = parseInt($li.css(&#39;margin-bottom&#39;))
            var  boderw= parseInt($(&#39;li&#39;).css(&#39;border-width&#39;))
            $ul.css({ &#39;heigth&#39;: (num * (y_height + topmar + boderw*2)) + &#39;px&#39; });
        }
        if(des.fangxiang == "left") {
            var  boderw= parseInt($(&#39;li&#39;).css(&#39;border-width&#39;))
            var rightmar = parseInt($li.css(&#39;margin-right&#39;))
            $ul.css({ &#39;width&#39;: (num * (x_width + rightmar+boderw*2)) + &#39;px&#39; });
        }
        var t;
        if(num > des.duoshaotu) {
            var t = setInterval(sidebarFlipAuto, des.sudu);
            function sidebarFlipAuto() {
                if(des.fangxiang == "left") {
                    $ul.stop(true, true).animate({ "left": (x_width + rightmar) + &#39;px&#39; }, 300, function() {
                        $ul.find(&#39;li:first&#39;).appendTo($ul);
                        $ul.css("left", &#39;0&#39;);
                    });
                }
                if(des.fangxiang == "top") {
                    $ul.stop(true, true).animate({ "top": (y_height + topmar) + &#39;px&#39; }, 300, function() {
                        $ul.find(&#39;li:first&#39;).appendTo($ul);
                        $ul.css("top", &#39;0&#39;);
                    });
                }
            }
            $ul.hover(function() {
                clearInterval(t);
            }, function() {
                t = setInterval(sidebarFlipAuto, 4000);
            })
            $ele.find(&#39;span&#39;).eq(0).unbind(&#39;click&#39;).click(function() {
                $ul.find(&#39;li:last&#39;).prependTo($ul);
                if(des.fangxiang == "left") {
                    $ul.css({ "left": (x_width + rightmar) + &#39;px&#39; });
                    $ul.stop(true, true).animate({ "left": &#39;0&#39; }, 300);
                }
                if(des.fangxiang == "top") {
                    $ul.css({ "top": (y_height + rightmar) + &#39;px&#39; });
                    $ul.stop(true, true).animate({ "top": &#39;0&#39; }, 300);
                }
            })
            $ele.find(&#39;span&#39;).eq(1).unbind(&#39;click&#39;).click(function() {
                sidebarFlipAuto();
            })
        }

    }
    
    那个.unbind(&#39;click&#39;).click不写这个有时会执行两次,所以百度了一下这个方法。
    求简洁化。

以上是javascript中的輪播圖插件化的封裝範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn