如何在我的自定义插件中绑定resize事件

时间:2015-02-06 08:22:19

标签: javascript jquery html html5 jquery-plugins

我正在创建一个定制的旋转木马,它的工作正常。

我拥有的: - 我有一个基本的代码,工作正常,旋转木马也可以在所有的屏幕和设备上正常工作。

我想要的: - 在更改分辨率以更改元素后,我必须重新加载。我希望我的插件自动加载其当前屏幕分辨率的设置。

我尝试过: -

HTML

    <!doctype html>
<html>
<head>
 <meta charset="utf-8" />
 <link href="s.css" rel="stylesheet" />
 <script src="jquery.min.js"></script>
 <meta name="viewport" content="widht=device-width, initial-scale=1" />
 <script src="s.js"></script>
 <script>
 $(window).load(function(){
    $( "#divstretch" ).Lslider(
    {
        SlideCount:5,
        SlideMargin:20,
        SmSlideCount : 3,
        XsSlideCount : 2
    });
    });
 </script>
 </head>
 <body>
 <div class="Demo-Slider">

<ul id="divstretch">
<li><img target="" class="gall-img-big1" src="demo.jpg"></li>
<li><a rel="group1" href="" class="fancybox"><img target="" class="gall-img-big1" src="demo.jpg"></a></li>

<li><a rel="group1" href="" class="fancybox"><img target="" class="gall-img-big1" src="demo.jpg"></a></li>

<li><a rel="group1" href="" class="fancybox"><img target="" class="gall-img-big1" src="demo.jpg"></a></li>

<li><a rel="group1" href="" class="fancybox"><img target="" class="gall-img-big1" src="demo.jpg"></a></li>

<li><a rel="group1" href="" class="fancybox"><img target="" class="gall-img-big1" src="demo.jpg"></a></li>

<li><a rel="group1" href="" class="fancybox"><img target="" class="gall-img-big1" src="demo.jpg"></a></li>

<li><a rel="group1" href="" class="fancybox"><img target="" class="gall-img-big1" src="demo.jpg"></a></li>

<li><a rel="group1" href="" class="fancybox"><img target="" class="gall-img-big1" src="demo.jpg"></a></li>

<li><a rel="group1" href="" class="fancybox"><img target="" class="gall-img-big1" src="demo.jpg"></a></li>

<li><a rel="group1" href="" class="fancybox"><img target="" class="gall-img-big1" src="demo.jpg"></a></li>

<li><a rel="group1" href="" class="fancybox"><img target="" class="gall-img-big1" src="demo.jpg"></a></li>

</ul>
</div>
</div>
 </body>
 </html>

JS

(function ($) {
  var SlideCount = null;
  var SlideMargin = null;
  var SmSlideCount = null;
  var XsSlideCount = null;

  $.fn.Lslider = function (options) {
    var Lcontainer = this;
    var settings = $.extend({
      // These are the defaults.
      SlideCount: 4,
      SmSlideCount: 3,
      XsSlideCount: 2,
      SlideMargin: 10
    }, options);
    return this.each(function () {
      // We'll get back to this in a moment
      SlideCount = settings.SlideCount;
      SlideMargin = settings.SlideMargin;
      SmSlideCount = settings.SmSlideCount
      XsSlideCount = settings.XsSlideCount;
      SlideCount = Math.round(SlideCount);
      SmSlideCount = Math.round(SmSlideCount);
      XsSlideCount = Math.round(XsSlideCount);
      //paramiters
      var LcontanerID = $(Lcontainer).attr('id')
      var bigImgArray = $(Lcontainer).children();
      //appending required html
      $(Lcontainer).wrap('<div class="Lslider-Main"><div class="Lslider"></div></div>');
      var Pcontainer = $(Lcontainer).parent();
      var parentwidth = $(Pcontainer).width();
      var SlideWidth = null;

       //creating prev and next nav
      var MainContainer = $(Pcontainer).parent();
      $(MainContainer).prepend('<a class="Lslide-left">Prev</a>');
      $(MainContainer).append('<a class="Lslide-right">Next</a>');
      var next = $('.Lslide-right');
      var prev = $('.Lslide-left');

      //previous button 
      $(prev).click(function () {
        var stretch = $(Lcontainer).css('left');
        stretch = stretch.replace('px', '');
        stretch = parseInt(stretch);
        var incStretch = stretch + LIwidth + SlideMargin;
        if (stretch < 0) {
          $(Lcontainer).animate({
            left: incStretch
          });
        }
      });
       //next button

      $(next).click(function () {
        var stretch = $(Lcontainer).css('left');
        stretch = stretch.replace('px', '');
        stretch = stretch.replace('-', '');
        stretch = parseInt(stretch);
        var incStretch = stretch + LIwidth + SlideMargin;
        var strechWidth1 = $(Lcontainer).width();
        var strechWidth2 = $(Lcontainer).parent().width();
        var strechWidth = strechWidth1 - strechWidth2 - LIwidth;
        if (stretch <= strechWidth || stretch == '') {
          $(Lcontainer).animate({
            left: - incStretch
          });
        }
      });

      //-------------------------------------//

      var WSize = $(window).width();
      var WHeight = $(window).height(); 
      if (WSize < 481) {
        SlideWidth = parentwidth / XsSlideCount;
      } 
      else if (WSize < 768) {
        SlideWidth = parentwidth / SmSlideCount;
      } 
      else {
        SlideWidth = parentwidth / SlideCount;
      }
      $(bigImgArray).width(SlideWidth - SlideMargin);
      $(bigImgArray).css('margin-right', SlideMargin)

      //appending the height and width to containers
      var totleLI = $(bigImgArray).length;
      var LIwidth = $(bigImgArray).width();
      var totalWidth = LIwidth * totleLI;
      var totleHeight = $(bigImgArray).height();

      $(Lcontainer).width(totalWidth);
      $(Lcontainer).height(totleHeight);
      $(Pcontainer).height(totleHeight);

    });
  }
}) (jQuery);

CSS

.Demo-Slider{
    width:500px;
    margin:0px auto;
    max-width:100%;
    position:relative;
}
@media only screen and (max-width:768px){
.Demo-Slider{
width:100%;
}
}
.Lslider{
    position:relative;
    overflow:hidden;
}
.Lslider ul li{
    width:115px;
    margin-right:10px;
    float:left;
    display:block;
}
.Lslider ul li img{
    max-width:100%;
}
.Lslider ul {
    margin:0px;
    padding:0px;
    left:0px;
    right:0px;
    position: absolute;
}
.Lslider-Main .Lslide-left{
    position: absolute;
    left: -20px;
    top: 0px;
    bottom: 0px;
    margin: auto;
    height: 30px;
}
.Lslider-Main .Lslide-right{
    position: absolute;
    right: -20px;
    top: 0px;
    bottom: 0px;
    margin: auto;
    height: 30px;
}

请查看代码并给我您的建议或解决方案。

3 个答案:

答案 0 :(得分:4)

方法1:

您可以将该函数绑定到resize事件。每次调整大小时它都会再次运行你的函数。如果在项目上运行代码两次会导致问题,这可能会导致问题。

$( window ).resize(function() {
  // Remove slider and redo
  $( "#divstretch" ).Lslider({
        SlideCount:5,
        SlideMargin:20,
        SmSlideCount : 3,
        XsSlideCount : 2
    });
});


方法2:

或者你可以在重新调整大小的函数中包装你想要重新运行的代码。它会自动调整。

$( window ).resize(function() {
  ....
  //appending the height and width to containers
  var totleLI = $(bigImgArray).length;
  var LIwidth = $(bigImgArray).width();
  var totalWidth = LIwidth * totleLI;
  var totleHeight = $(bigImgArray).height();

  $(Lcontainer).width(totalWidth);
  $(Lcontainer).height(totleHeight);
  $(Pcontainer).height(totleHeight);
  ....
});


只需确保在加载时触发调整大小代码。

$(window).trigger('resize');

答案 1 :(得分:2)

我认为实现目标的最佳方式是:

  1. 传入布尔responsive标志并从插件中绑定窗口大小调整侦听器。

  2. 创建一个公共方法,将滑块设置为适当的大小,然后在插件外部,将其绑定到窗口大小调整事件。

  3. 我重新编写了这个插件,以便它拥有自己的构造函数和方法,允许你跟踪Lslider实例,并在需要时调用它的公共方法。

    我应该强调,这不是一个完整的解决方案。我只对它进行了最低限度的测试,以确保它没有错误。我还选择不实现nextprev方法,因为确切的实现取决于您的标记和样式;相反,我把它作为锻炼给你。

    非常糟糕的演示,只显示初始化和调整响应速度。 http://codepen.io/shawkdsn/pen/gbKMNK

    注意:要使用$ .debounce,必须定义,您可以在此处找到实现:http://benalman.com/projects/jquery-throttle-debounce-plugin/

    (function($){
    
      var defaults = {
        slideCount    : 4,
        smSlideCount  : 3,
        xsSlideCount  : 2,
        slideMargin   : 10,
        responsive    : false, // whatever default you want
        debounceTime  : 50     // whatever default you want
      };
    
      // constructor
      var Lslider = function(el, options) {
        this.el = $(el);
        this.settings = $.extend({}, defaults, options);
    
        // save a reference to the Lslider instance
        this.el.data('Lslider', this);
        this.initialize();
      };
    
      Lslider.prototype.initialize = function() {
        this.setVars();
        this.wrapDom();
        this.createNavigation();
        this.bindEvents();
        this.setSize();
      };
    
      Lslider.prototype.setVars = function() {
        var s = this.settings;
    
        this.images = this.el.children();
    
        s.SlideCount = Math.round(s.slideCount);
        s.SmSlideCount = Math.round(s.smSlideCount);
        s.XsSlideCount = Math.round(s.xsSlideCount);
      };
    
      Lslider.prototype.wrapDom = function() {
        this.el.wrap('<div class="Lslider-Main"><div class="Lslider"></div></div>');
        this.elParent      = this.el.parent();
        this.elParentWidth = this.elParent.width();
        this.mainContainer = this.elParent.parent();
      };
    
      Lslider.prototype.createNavigation = function() {
        this.mainContainer.append('<a class="Lslide-next">Next</a>');
        this.mainContainer.prepend('<a class="Lslide-prev">Prev</a>');
        this.navNext = this.mainContainer.find('.Lslide-next');
        this.navPrev = this.mainContainer.find('.Lslide-prev');
      };
    
      Lslider.prototype.bindEvents = function() {
        this.mainContainer.on('click', '.Lslide-next', this.next.bind(this));
        this.mainContainer.on('click', '.Lslide-prev', this.prev.bind(this));
    
        if(this.settings.responsive) {
          $(window).on('resize',
            $.debounce(this.settings.debounceTime, this.setSize.bind(this))
          )
        }
      };
    
      Lslider.prototype.next = function() {
        // some code to show the next item
      };
    
      Lslider.prototype.prev = function() {
        // some code to show the previous item
      };
    
      Lslider.prototype.setSize = function() {
        var windowWidth  = $(window).width();
        var windowHeight = $(window).height();
        var imagesCount  = this.images.length;
        var imagesWidth  = this.images.width();
        var totalWidth   = imagesWidth * imagesCount;
        var totalHeight  = this.images.height();
    
        if (windowWidth < 481) {
          this.slideWidth = this.elParentWidth / this.settings.xsSlideCount;
        } 
        else if (windowWidth < 768) {
          this.slideWidth = this.elParentWidth / this.settings.smSlideCount;
        } 
        else {
          this.slideWidth = this.elParentWidth / this.slideCount;
        }
    
        this.images.each(function(i, el) {
          $(el).width(this.slideWidth - this.slideMargin);
          $(el).css('margin-right', this.slideMargin);
        }.bind(this));
    
        this.el.width(totalWidth).height(totalHeight);
        this.elParent.height(totalHeight);
      };
    
      $.fn.Lslider = function (options) {
        return this.each(function () {
          return new Lslider(this, options);
        })
      }
    })(jQuery);
    

    然后在您的页面中,您需要做的就是初始化插件并传递responsive: true标志:

    // grab a reference to the slider element
    var $slider = $('#divstretch');
    
    // instantiate the plugin, passing options
    $slider.Lslider({
      slideCount    : 5,
      slideMargin   : 20,
      smSlideCount  : 3,
      xsSlideCount  : 2,
      responsive    : true,
      debounceTime  : 100
    });
    
    // If you'd prefer to wire up the listener outside your
    // plugin then you could do something like the following,
    // (without passing the responsive flag)
    $(window).on('resize', $.debounce(100, function() {
      // use $.fn.data to get the Lslider instance and call it's `setSize` method
      $slider.data('Lslider').setSize();
    }));
    

    更好的方法是跟踪对象中的大小并将其作为选项传递。只是为了证明:

    var sizes = {
      0:   1 // above 0px, show 1 item
      480: 2 // above 480px, show 2 items
      768: 3 // above 768px, show 3 items
    }
    
    // in `setSize`
    var windowWidth = parseInt($(window).width(), 10);
    
    // loop over the keys in the `sizes` object
    var numberOfItems = Object.keys(this.settings.sizes).reduce(function(result, size) {
      // for each size, compare it to the window width
      // if the window is wider, save the item count
      if (windowWidth >= size) return result = sizes[size];
    });
    

    编辑:修正了代码错误

答案 2 :(得分:0)

您可以使用以下代码,而不是为加载和调整大小事件编写代码。

  $( window ).on('load resize',function() {
    $( "#divstretch" ).Lslider({
        SlideCount:5,
        SlideMargin:20,
        SmSlideCount : 3,
        XsSlideCount : 2
    });
 });
相关问题