Swiper slider not working unless page is resized

2020-02-06 06:40发布

问题:

Im trying to add the Swiper plugin to one of my page. What im trying to achieve is to integrate get the carousal slider over here http://idangero.us/swiper/demos/05-slides-per-view.html

HTML

 <div class="swiper-container">
    <div class="swiper-wrapper">
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    <div class="swiper-slide">Slide 3</div>
    <div class="swiper-slide">Slide 4</div>
    <div class="swiper-slide">Slide 5</div>
    <div class="swiper-slide">Slide 6</div>
    <div class="swiper-slide">Slide 7</div>
    <div class="swiper-slide">Slide 8</div>
    <div class="swiper-slide">Slide 9</div>
    <div class="swiper-slide">Slide 10</div>
    </div>

    <div class="swiper-pagination"></div>
    </div>

JS

var swiper = new Swiper('.swiper-container', {
        pagination: '.swiper-pagination',
        slidesPerView: 3,
        paginationClickable: true,
        spaceBetween: 30,
        // Navigation arrows
    nextButton: '.swiper-button-next',
    prevButton: '.swiper-button-prev',
    });

When i add it to a fiddle it works but when i add to my html page, the swiper doesnt work until i open firebug or resize the page (http://vidznet.com/ng1/swiper/swipe.html) Im not sure if its conflicting when initializing because There are no errors in the console.

After spending some time I thought it might be a jquery issue and wrapped the coding inside a

pagebeforecreate

 $(document).on( "pagebeforecreate", "#new_",function( event ) { 

but still the same,

I also added the below code

swiper.updateContainerSize();

which is supposed to update the container size, but still not working.

Any help will be much appreciated.

回答1:

Swiper's sliders, in order to work properly, requires you to either:

  • initialize them when they are visible;
  • update them when they get visible;
  • enable observer paramenters.
    • observer: true;
    • observeParents: true.

As stated by Isaiahiroko and Swiper's creator (on this issue), executing one of the mentioned topics will solve your issue, for sure!



回答2:

Use this code:

swiper.update();


回答3:

you could try :

$(window).on({
   load: function(){
      $(this).trigger('resize');
    } 
  });

though it's a bit of a stickytape solution.



回答4:

I tried below code it worked for me my swiper was present inside a tab, when my document is loaded swipper was not working unless and unless I resize the screen,so i tried below code it worked

var swiper = new Swiper('#upcoming-appointments', {
        slidesPerView: 1,
        spaceBetween: 30,
        loop: true,
        pagination: {
            el: '.swiper-pagination',
            clickable: true,
        },
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },
//<---Add this two lines in your code-->   
       observer: true,  
       observeParents: true,
    });