在網(wǎng)站開發(fā)過程中,我們用得很多的插件之一就是swiper,但是我們在做左右多個(gè)slider切換的時(shí)候,當(dāng)換到手機(jī)端上的時(shí)候,我們需要切換顯示的個(gè)數(shù)。如果下圖:
比如PC端一行顯示4個(gè)圖片:
JS:
var swiper = new Swiper('.swiper-container', { slidesPerView: 4, spaceBetween: 30, loop: true, autoplay:true, speed: 500, // 如果需要分頁器 pagination: { el: '.swiper-pagination', clickable :true, }, // 如果需要前進(jìn)后退按鈕 navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, });
但是顯示在手機(jī)上不能顯示4個(gè),需要顯示1個(gè)或者兩個(gè)。
var swiper = new Swiper('.swiper-container', { slidesPerView: 1, spaceBetween: 30, loop: true, autoplay:true, speed: 500, // 如果需要分頁器 pagination: { el: '.swiper-pagination', clickable :true, }, // 如果需要前進(jìn)后退按鈕 navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, });
那么我們就可以通過JS來監(jiān)聽窗口的大小變化來調(diào)用不同的代碼。
代碼如下:
//打開網(wǎng)頁時(shí)的寬度,必須保留 var windowsize = $(window).width(); if( windowsize > 768 ) { // 屏寬1330觸發(fā) //主體 var swiper = new Swiper('.swiper-container', { slidesPerView: 4, spaceBetween: 30, loop: true, autoplay:true, speed: 500, // 如果需要分頁器 pagination: { el: '.swiper-pagination', clickable :true, }, // 如果需要前進(jìn)后退按鈕 navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, }); //主體 }else{ //主體 var swiper = new Swiper('.swiper-container', { slidesPerView: 1, spaceBetween: 30, loop: true, autoplay:true, speed: 500, // 如果需要分頁器 pagination: { el: '.swiper-pagination', clickable :true, }, // 如果需要前進(jìn)后退按鈕 navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, }); //主體 } //監(jiān)測網(wǎng)頁時(shí)的寬度變化,以及實(shí)時(shí)更新 $(window).resize(function() { windowsize = $(window).width(); if( windowsize > 768 ) { // 屏寬1330觸發(fā) //主體 var swiper = new Swiper('.swiper-container', { slidesPerView: 4, spaceBetween: 30, loop: true, autoplay:true, speed: 500, // 如果需要分頁器 pagination: { el: '.swiper-pagination', clickable :true, }, // 如果需要前進(jìn)后退按鈕 navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, }); //主體 }else{ //主體 var swiper = new Swiper('.swiper-container', { slidesPerView: 1, spaceBetween: 30, loop: true, autoplay:true, speed: 500, // 如果需要分頁器 pagination: { el: '.swiper-pagination', clickable :true, }, // 如果需要前進(jìn)后退按鈕 navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, }); //主體 } });
以上是用JS來寫的?,F(xiàn)在提供另一方法 就是swiper自帶的效果:
var swiper = new Swiper('.swiper-container', { slidesPerView: 4, spaceBetween: 30, loop: true, autoplay:true, speed: 500, // 如果需要分頁器 pagination: { el: '.swiper-pagination', clickable :true, }, // 如果需要前進(jìn)后退按鈕 navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, //響應(yīng)式個(gè)數(shù) breakpoints: { //當(dāng)寬度小于等于640時(shí)顯示 640: { slidesPerView: 1, spaceBetween: 20 }, //當(dāng)寬度小于等于768時(shí)顯示 768: { slidesPerView: 3, spaceBetween: 30 }, //當(dāng)寬度小于等于992時(shí)顯示 992: { slidesPerView: 4, spaceBetween: 30 } } });