change number of slides on bxslider depending on s

2019-03-17 03:59发布

问题:

I want to change the max number of slides on the bxslider for when my screen is below 430px.

I could use the below but this seems like overkill having to declare everything twice. Is there any other way that someone could think of?

    if ( $(window).width() < 430) {
    var myslider = $('#my-slider').bxSlider({
        ...
        maxSlides       : 1,
    });  
    }

    else {
    var myslider = $('#my-slider').bxSlider({
        ...
        maxSlides       : 4,
    });
    }

回答1:

You can make things less repetitive by setting a maxSlides variable, rather than repeating your slider code.

var maxSlides,
    width = $(window).width();

if (width < 430) {
    maxSlides = 1;
} else {
    maxSlides = 4;
}

var myslider = $('#my-slider').bxSlider({
    ...
    maxSlides: maxSlides,
});

You could make it even simpler with a ternary operator, though trying to get too concise is not necessarily a benefit.

var width = $(window).width();

var myslider = $('#my-slider').bxSlider({
    ...
    maxSlides: (width < 430) ? 1 : 4,
});


回答2:

Here is a responsive solution that will dynamically adjust the settings as you resize the window:

var slider,
  oBxSettings = { /* Your bxSlider settings */ };

function init() {
  // Set maxSlides depending on window width
  oBxSettings.maxSlides = window.outerWidth < 430 ? 1 : 4;
}

$(document).ready(function() {
  init();
  // Initial bxSlider setup
  slider = $('#my-slider').bxSlider(oBxSettings);
});

$(window).resize(function() {
  // Update bxSlider when window crosses 430px breakpoint
  if ((window.outerWidth<430 && window.prevWidth>=430)
    || (window.outerWidth>=430 && window.prevWidth<430)) {
    init();
    slider.reloadSlider(oBxSettings);
  }
  window.prevWidth = window.outerWidth;
});


回答3:

I use it like this with jquery:

 var windowWidth = $(window).width();  
 var obxSettings = {...};
 slider.bxSlider(obxSettings);

 $(window).resize(function() {
    windowWidth = $(window).width();
    if(windowWidth < 768) {
    obxSettings.minSlides = 2;
    slider.reloadSlider();
 }   
 else {
    obxSettings.minSlides = 3;
    slider.reloadSlider();
 }
 });