简体   繁体   中英

How can I have multiple Swiper slideshows on a single page?

I'm using Swiper Slideshow . I'm using this particular version . Here's the exact code I'm using.

When adding a second Swiper, the pagination doesn't work properly.

I tried giving a different class to the second Swiper container but it didn't work.

How can I have two of this in the same page?

Thanks.

Their support sent me this DEMO . It works!

You don't need to do anything to the JS File. All you need is to add an extra class to pagination, add an extra class also to the slideshow, and differentiate the rest of the classes on everything else (see code below). With this you can have as many slishows as you want in the same page.

<div class="swiper-container swiper1">
        <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>
        <!-- Add Pagination -->
        <div class="swiper-pagination swiper-pagination1"></div>
    </div>

    <!-- Swiper -->
    <div class="swiper-container swiper2">
        <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>
        <!-- Add Pagination -->
        <div class="swiper-pagination swiper-pagination2"></div>

 <!-- Swiper JS -->
    <script src="../dist/js/swiper.min.js"></script>

<!-- Initialize Swiper -->
<script>
var swiper1 = new Swiper('.swiper1', {
    pagination: '.swiper-pagination1',
    paginationClickable: true,
});
var swiper2 = new Swiper('.swiper2', {
    pagination: '.swiper-pagination2',
    paginationClickable: true,
});
<script>

In case someone is passing here in search for a solution to conflicts with prev and next button between multiple swipers, this is what fixed it for me (Nuxt.js/SSR project):

1) Add id attributes to button's divs: <div id="button-next-relacionados" class="swiper-button-next swiper-button-white"></div> <div id="button-next-relacionados" class="swiper-button-next swiper-button-white"></div>

2) In the swiper options object, refer to the new ids instead of swiper-button-prev and swiper-button-next classes:

swiperOption: {
        direction: 'horizontal',
        slidesPerView: 4,
        spaceBetween: 6,
        navigation: {
          nextEl: '#button-next-relacionados',
          prevEl: '#button-prev-relacionados'
        },

I had a case where I needed 3 identical sliders on the same page and I didn't want to duplicate any code, nor did I want to hardcode anything. This is how I solved it 👇

// Function that actually builds the swiper 
const buildSwiperSlider = sliderElm => {
    const sliderIdentifier = sliderElm.dataset.id;
    return new Swiper(`#${sliderElm.id}`, {
        navigation: {
            nextEl: `.swiper-button-next-${sliderIdentifier}`,
            prevEl: `.swiper-button-prev-${sliderIdentifier}`
        },
        pagination: {
            el: `.swiper-pagination-${sliderIdentifier}`,
            type: 'progressbar',
        },
    });
}

// Get all of the swipers on the page
const allSliders = document.querySelectorAll('.swiper');

// Loop over all of the fetched sliders and apply Swiper on each one.
allSliders.forEach(slider => buildSwiperSlider(slider));

As you can see from the above code the key here is assigning an identifier to each of the sliders. In my case, I opted to use a data-id property and reference that. Like this 👇

<div class="swiper" data-id="ID_OF_FIRST_SLIDER">
...
</div>
<div class="swiper" data-id="ID_OF_SECOND_SLIDER">
...
</div>
<div class="swiper" data-id="ID_OF_THIRD_SLIDER">
...
</div>

And pagination/navigation element just incorporate the identifier as part of their class name.

My current Swiper version is 3.4.2. When I click on the next-prev button, all the sliders on the page moves.

For set different next-prev buttons I done this:

<div class="swiper-pager">
  <div class="swiper-button-next></div>
  <div class="swiper-button-prev></div>
</div>

=>

<div class="swiper-pager">
  <div class="swiper-button-next swiper-button-next_slideshow<?=$module?>"></div>
  <div class="swiper-button-prev swiper-button-prev_slideshow<?=$module?>"></div>
</div>

And in js:

$('#slideshow<?=$module?>').swiper({
  mode: 'horizontal',
  slidesPerView: 1,
  pagination: '.slideshow<?=$module?>',
  paginationClickable: true,
  // nextButton: '.swiper-button-next', // not work properly
  // prevButton: '.swiper-button-prev', // not work properly
  nextButton: '.swiper-button-next_slideshow<?=$module?>',
  prevButton: '.swiper-button-prev_slideshow<?=$module?>',
  spaceBetween: 30,
  autoplay: 2500,
  autoplayDisableOnInteraction: true,
  loop: true
});

@David Martins Thanks a lot, but in current version 4.5.0, you need to modify a little js code:

<script type="text/javascript">
// Init Swiper
var swiper1 = new Swiper('.swiper1', {
  pagination: {
    el: '.swiper-pagination1',
    clickable: true,
  },
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  },
  // Enable debugger
  debugger: true,
});
var swiper2 = new Swiper('.swiper2', {
  autoHeight: true,
  pagination:  {
    el: '.swiper-pagination2',
    clickable: true,
  },
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  },
  // Enable debugger
  debugger: true,
});

anyway, thanks a lot for help!

  1. add another class like:

     class="swiper-container two" ...
  2. append the class in js like:

     new Swiper('.swiper-container.two', { ...

This is how it worked for me

Here's a nice easy Vanilla Javascript way of doing it

just change the 'large-slider' class to whatever you're using as your slider name, same with the prevs and next classes for the arrows.

full example here on codepen

https://codepen.io/davenoham/pen/YzQWdge

const largeSlider = ()=>{
let largeSliders = document.querySelectorAll('.large-swiper')
let prevArrow = document.querySelectorAll('.prev')
let nextArrow = document.querySelectorAll('.next')
largeSliders.forEach((slider, index)=>{
    let sliderLength = slider.children[0].children.length
    let result = (sliderLength > 1) ? true : false
    const swiper = new Swiper(slider, {
        direction: 'horizontal',
        loop: result,
        navigation: {
            nextEl: nextArrow[index],
            prevEl: prevArrow[index],
        },
        speed: 1000,
    }); 
})

} window.addEventListener('load', largeSlider)

var i=1;
var str1='sliderBox_'
var str2='.sliderBox_';
$('.swiper-container').each(function (index,value) {

    var classAdd = str1 + i;
    var classCall = str2 + i;
    var next_slider = 'slider-next' + i;
    var prev_slider = 'slider-prev' + i;
    $(this).addClass(classAdd);
    $(this).parent().siblings(".sites-slider__prev").addClass(prev_slider);
    $(this).parent().siblings(".sites-slider__next").addClass(next_slider);
    new Swiper(classCall,{
        slidesPerView: 4,
        spaceBetween: 20,
        loop: true,
        navigation: {
            nextEl: ('.' + next_slider),
            prevEl: ('.' + prev_slider),
        },
        breakpoints: {
            1199: {
                slidesPerView: 3,
            },
            991: {
                slidesPerView: 2,
            },
            600: {
                slidesPerView: 1,
            },
        }
    });
    i++;



});

You were going down the right path - you need to add a different class to the second swiper but you also need to add references to the new class in dist/js/swiper.min.js otherwise it will only be targeting elements using the original class. It should just be a case of copying the relevant sections and repeating them with the new ID (same as what I had to do with wow.js).

In my case, the issue was with using multiple auto-initialized instances while using Framework7 Core to update slide results based on the data values.

The missing piece for this use case was assigning an id to the swiper container, for example:

<div class="swiper-container swiper-init" id="swiper-instance-{{
userId}}">

This little bit of magic causes everything to work again, otherwise it tries to re-use the Swiper instances and gets very confused about which one the instance belongs to. Once again Vladimir has thought of everything :)

(Example in CodePen: https://codepen.io/rasaf-ibrahim/pen/mdrVQEq )

We need to add extra classes on HTML and change classes on CSS and JS to make multiple swiper slideshow work in a single page.

Step-1: Let's first take a look at the HTML files of the swiper slideshow

<!— HTML of swiper-1 -->

   <div class="swiper-container">
    <div class="swiper-wrapper">
      <div class="swiper-slide" style="background-image:url(https://source.unsplash.com/800x600/?car)"></div>
      <div class="swiper-slide" style="background-image:url(https://source.unsplash.com/800x600/?tree)"></div>
      <div class="swiper-slide" style="background-image:url(https://source.unsplash.com/800x600/?tiger)"></div>
      <div class="swiper-slide" style="background-image:url(https://source.unsplash.com/800x600/?water)"></div>
      <div class="swiper-slide" style="background-image:url(https://source.unsplash.com/800x600/?dog)"></div>
    </div>

    <!-- Swiper - Add Pagination -->
    <div class="swiper-pagination"></div>
  </div>

<!—HTML of swiper-2 -->

<div class="swiper-container ">
   <div class="parallax-bg" style="background-image:url(https://source.unsplash.com/800x600/?space)" data-swiper-parallax="-23%"></div>
  <div class="swiper-wrapper">
    <div class="swiper-slide">
      <div class="title" data-swiper-parallax="-300">Slide 1</div>
      <div class="subtitle" data-swiper-parallax="-200">Subtitle</div>
      <div class="text" data-swiper-parallax="-100">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam dictum mattis velit, sit amet faucibus
          felis iaculis nec. Nulla laoreet justo vitae porttitor porttitor. Suspendisse in sem justo. </p>
      </div>
    </div>
    <div class="swiper-slide">
      <div class="title" data-swiper-parallax="-300" data-swiper-parallax-opacity="0">Slide 2</div>
      <div class="subtitle" data-swiper-parallax="-200">Subtitle</div>
      <div class="text" data-swiper-parallax="-100">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam dictum mattis velit, sit amet faucibus
          felis iaculis nec. Nulla laoreet justo vitae porttitor porttitor. Suspendisse in sem justo. </p>
      </div>
    </div>
    <div class="swiper-slide">
      <div class="title" data-swiper-parallax="-300">Slide 3</div>
      <div class="subtitle" data-swiper-parallax="-200">Subtitle</div>
      <div class="text" data-swiper-parallax="-100">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam dictum mattis velit, sit amet faucibus
          felis iaculis nec. Nulla laoreet justo vitae porttitor porttitor. Suspendisse in sem justo. Integer laoreet
         </p>
      </div>
    </div>
  </div>
  <!-- Add Pagination -->
  <div class="swiper-pagination swiper-pagination-white"></div>
  <!-- Add Navigation -->
  <div class="swiper-button-prev swiper-button-white"></div>
  <div class="swiper-button-next swiper-button-white"></div>
</div>

Step -2: Let's first Identify classes that are common in the CSS file of both swiper slideshow.

/* CSS of swiper-1 */

   
    .swiper-container {
      width: 100%;
      padding-top: 50px;
      padding-bottom: 50px;
    }

    .swiper-slide {
      background-position: center;
      background-size: cover;
      width: 300px;
      height: 300px;

    }

/* CSS of swiper-2 */

.swiper-container {
    position: relative;
    height: 100%;
    background: #eee;
    font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
    font-size: 14px;
    color: #000;
    margin: 0;
    padding: 0;
  
width: 100%;
  height: 100%;
  background: #000;
}

.swiper-slide {
  font-size: 18px;
  color: white;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  padding: 40px 60px;
}

.parallax-bg {
  position: absolute;
  left: 0;
  top: 0;
  width: 130%;
  height: 100%;
  -webkit-background-size: cover;
  background-size: cover;
  background-position: center;

}

.swiper-slide .title {
  font-size: 41px;
  font-weight: 300;
}

.swiper-slide .subtitle {
  font-size: 21px;
}

.swiper-slide .text {
  font-size: 14px;
  max-width: 400px;
  line-height: 1.3;

}

As we can see, .swiper-container and .swiper-slide are common classes

Step -3: Now, let's identify classes that are common in the JS file of both swiper slideshow.

// JS File of Swiper-1

var swiper = new Swiper('.swiper-container ', {
    effect: 'coverflow',
    grabCursor: true,
    centeredSlides: true,
    slidesPerView: 'auto',
    coverflowEffect: {
      rotate: 50,
      stretch: 0,
      depth: 100,
      modifier: 1,
      slideShadows: true,
    },
    pagination: {
      el: '.swiper-pagination',
    },
  });

// JS file of swiper-2

var swiper = new Swiper('.swiper-container', {
    speed: 600,
    parallax: true,
    pagination: {
      el: '.swiper-pagination',
      clickable: true,
    },
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev',
    },
  });

As we can see, .swiper-container and .swiper-pagination are common classes

Step-4: Now let's add extra classes on the common classes (.swiper-container .swiper-slide .swiper-pagination) of the HTML file

<!— HTML of swiper-1 -->

  <div class="swiper-container swiper-container1">
    <div class="swiper-wrapper">
      <div class="swiper-slide swiper-slide1" style="background-image:url(https://source.unsplash.com/800x600/?car)"></div>
      <div class="swiper-slide swiper-slide1" style="background-image:url(https://source.unsplash.com/800x600/?tree)"></div>
      <div class="swiper-slide swiper-slide1" style="background-image:url(https://source.unsplash.com/800x600/?tiger)"></div>
      <div class="swiper-slide swiper-slide1" style="background-image:url(https://source.unsplash.com/800x600/?water)"></div>
      <div class="swiper-slide swiper-slide1" style="background-image:url(https://source.unsplash.com/800x600/?dog)"></div>
      </div>

    <!-- Swiper - Add Pagination -->
    <div class="swiper-pagination swiper-pagination1"></div>
  </div>


    <!—HTML of swiper-2 -->

<div class="swiper-container swiper-container2">
  <div class="parallax-bg" style="background-image:url(https://source.unsplash.com/800x600/?space)" data-swiper-parallax="-23%"></div>
  <div class="swiper-wrapper">
    <div class="swiper-slide  swiper-slide2">
      <div class="title" data-swiper-parallax="-300">Slide 1</div>
      <div class="subtitle" data-swiper-parallax="-200">Subtitle</div>
      <div class="text" data-swiper-parallax="-100">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam dictum mattis velit, sit amet faucibus
          felis iaculis nec. Nulla laoreet justo vitae porttitor porttitor. Suspendisse in sem justo.</p>
      </div>
    </div>
    <div class="swiper-slide swiper-slide2">
      <div class="title" data-swiper-parallax="-300" data-swiper-parallax-opacity="0">Slide 2</div>
      <div class="subtitle" data-swiper-parallax="-200">Subtitle</div>
      <div class="text" data-swiper-parallax="-100">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam dictum mattis velit, sit amet faucibus
          felis iaculis nec. Nulla laoreet justo vitae porttitor porttitor. Suspendisse in sem justo. </p>
      </div>
    </div>
    <div class="swiper-slide swiper-slide2">
      <div class="title" data-swiper-parallax="-300">Slide 3</div>
      <div class="subtitle" data-swiper-parallax="-200">Subtitle</div>
      <div class="text" data-swiper-parallax="-100">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam dictum mattis velit, sit amet faucibus
          felis iaculis nec. Nulla laoreet justo vitae porttitor porttitor. Suspendisse in sem justo.</p>
      </div>
    </div>
  </div>
  <!-- Add Pagination -->
  <div class="swiper-pagination swiper-pagination2 swiper-pagination-white"></div>
  <!-- Add Navigation -->
  <div class="swiper-button-prev swiper-button-white"></div>
  <div class="swiper-button-next swiper-button-white"></div>
</div>

Step-5: Now let's change those common classes with the newly added classes on both CSS and JS.

CSS:

/*  CSS of swiper-1 */

   
    .swiper-container1{
      width: 100%;
      padding-top: 50px;
      padding-bottom: 50px;
    }

    .swiper-slide1 {
      background-position: center;
      background-size: cover;
      width: 300px;
      height: 300px;

    }
  
/* CSS of swiper-2 */

.swiper-container2{
  position: relative;
  height: 100%;
  background: #eee;
  font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
  font-size: 14px;
  color: #000;
  margin: 0;
  padding: 0;

width: 100%;
height: 100%;
background: #000;
}

.swiper-slide2 {
font-size: 18px;
color: white;
-webkit-box-sizing: border-box;
box-sizing: border-box;
padding: 40px 60px;
}

.parallax-bg {
position: absolute;
left: 0;
top: 0;
width: 130%;
height: 100%;
-webkit-background-size: cover;
background-size: cover;
background-position: center;

}

.swiper-slide .title {
font-size: 41px;
font-weight: 300;
}

.swiper-slide .subtitle {
font-size: 21px;
}

.swiper-slide .text {
font-size: 14px;
max-width: 400px;
line-height: 1.3;

}

JS:

//  JS of swiper-1

var swiper = new Swiper('.swiper-container1', {
    effect: 'coverflow',
    grabCursor: true,
    centeredSlides: true,
    slidesPerView: 'auto',
    coverflowEffect: {
      rotate: 50,
      stretch: 0,
      depth: 100,
      modifier: 1,
      slideShadows: true,
    },
    pagination: {
      el: '.swiper-pagination1',
    },
  });


  // JS of swiper-2 

var swiper = new Swiper('.swiper-container2', {
  speed: 600,
  parallax: true,
  pagination: {
    el: '.swiper-pagination2',
    clickable: true,
  },
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  },
});

This seem to work for me using in nuxtjs with multiple swipers on page

used id instead of class in options

   <div
      :id="`swiper-button-prev-${element}`"
      class="swiper-button-prev"
    ></div>
    <div
      :id="`swiper-button-next-${element}`"
      class="swiper-button-next"
    ></div>

... Options:

navigation: {
  nextEl: `#swiper-button-next-${this.element}`,
  prevEl: `#swiper-button-prev-${this.element}`,
},

to get unique id, I used

https://www.npmjs.com/package/uuid

example of generated output: element: 47bfe557-d75f-455c-9a37-85b7935b297b

package.json

"dependencies": {    
    "uuid": "^8.3.2"
 },

on child component, might not be the best way but seem to work

...

<ComponentName v-if="element" />

...

import { v4 as uuidv4 } from 'uuid';

...

data() {
  return {
    element: null,
  }
}

...

mounted() {
  this.element = uuidv4();
}

there is a simple solution for it. you can just create navigation dynamically by enabling {createElements: true}. It will generate navigation dynamically you also need to enable navigation to add navigation into dom. otherwise nothing will happen

 new Swiper('.color-carousel', { slidesPerView: 8, spaceBetween: 8, loop: true, modules: [Navigation], navigation: true, createElements: true, });

here is the official docs https://swiperjs.com/swiper-api#param-createElements

It is not necessary to increment the button classes.

Make sure they are already present in the DOM and that they are children of the parent element declared in the "new Swiper() function". They will work in the context of their parent only.

Simply specify your swiper for each use in a page.

Personally, I prefer to target my swipers by unique ids. Something like this:

<div class="swiper-container" id="swiper-top">
    <div class="swiper-wrapper">
        <div class="swiper-slide"></div>
        <div class="swiper-slide"></div>
        <div class="swiper-slide"></div>
        <div class="swiper-slide"></div>
    </div>
    <div class="swiper-pagination"></div>
    <button class="swiper-button-prev"></button>
    <button class="swiper-button-next"></button>
</div>

Then use this unique id as an initializer:

var swiper = new Swiper("#swiper-top", {
    slidesPerView: 4,
    spaceBetween: 12,
    grabCursor: true,
    pagination: {
        el: '.swiper-pagination',
    },
    navigation: {
        prevEl: ".swiper-button-prev",
        nextEl: ".swiper-button-next",
    }
});

Note that my buttons are initialized in the function, although they are already present in the DOM. So you don't need to give them a different class each time.

Hope you find it useful !

 swiperOption: { direction: 'horizontal', slidesPerView: 4, spaceBetween: 6, navigation: { nextEl: '#button-next-relacionados', prevEl: '#button-prev-relacionados' }
 <div id="button-next-relacionados" class="swiper-button-next swiper-button-white"></div> <div id="button-next-relacionados" class="swiper-button-next swiper-button-white"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM