在网站开发过程中,我们用得很多的插件之一就是swiper,但是我们在做左右多个slider切换的时候,当换到手机端上的时候,我们需要切换显示的个数。如果下图:
比如PC端一行显示4个图片:
JS:
var swiper = new Swiper('.swiper-container', {
slidesPerView: 4,
spaceBetween: 30,
loop: true,
autoplay:true,
speed: 500,
// 如果需要分页器
pagination: {
el: '.swiper-pagination',
clickable :true,
},
// 如果需要前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
但是显示在手机上不能显示4个,需要显示1个或者两个。
var swiper = new Swiper('.swiper-container', {
slidesPerView: 1,
spaceBetween: 30,
loop: true,
autoplay:true,
speed: 500,
// 如果需要分页器
pagination: {
el: '.swiper-pagination',
clickable :true,
},
// 如果需要前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
那么我们就可以通过JS来监听窗口的大小变化来调用不同的代码。
代码如下:
//打开网页时的宽度,必须保留
var windowsize = $(window).width();
if( windowsize > 768 ) { // 屏宽1330触发
//主体
var swiper = new Swiper('.swiper-container', {
slidesPerView: 4,
spaceBetween: 30,
loop: true,
autoplay:true,
speed: 500,
// 如果需要分页器
pagination: {
el: '.swiper-pagination',
clickable :true,
},
// 如果需要前进后退按钮
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,
},
// 如果需要前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
//主体
}
//监测网页时的宽度变化,以及实时更新
$(window).resize(function() {
windowsize = $(window).width();
if( windowsize > 768 ) { // 屏宽1330触发
//主体
var swiper = new Swiper('.swiper-container', {
slidesPerView: 4,
spaceBetween: 30,
loop: true,
autoplay:true,
speed: 500,
// 如果需要分页器
pagination: {
el: '.swiper-pagination',
clickable :true,
},
// 如果需要前进后退按钮
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,
},
// 如果需要前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
//主体
}
});
以上是用JS来写的。现在提供另一方法 就是swiper自带的效果:
var swiper = new Swiper('.swiper-container', {
slidesPerView: 4,
spaceBetween: 30,
loop: true,
autoplay:true,
speed: 500,
// 如果需要分页器
pagination: {
el: '.swiper-pagination',
clickable :true,
},
// 如果需要前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
//响应式个数
breakpoints: {
//当宽度小于等于640时显示
640: {
slidesPerView: 1,
spaceBetween: 20
},
//当宽度小于等于768时显示
768: {
slidesPerView: 3,
spaceBetween: 30
},
//当宽度小于等于992时显示
992: {
slidesPerView: 4,
spaceBetween: 30
}
}
});