javascript - 切换多个swiper之后滑动轮播图底下的分页器不动了?
本文介绍了javascript - 切换多个swiper之后滑动轮播图底下的分页器不动了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
https://jsfiddle.net/aLq1b11f/
使用swiper进行轮播效果,出现了一个奇怪的问题,不知是不是bug,
多次点击切换button之后 ,滑动轮播图,底下的分页小点点就不动了?
解决方案
之前没用过Swiper,专门去官网看了一下demo和API。
楼主的问题不是Swiper插件出现Bug,而是你在createSwiper()函数中,用一个局部变量"var swiper = Swiper()"去创建一个Swiper实例后,再次调用createSwiper()函数时,没有对之前创建的实例进行释放,从而出现问题。
刚才测试了一下,你的方法不清楚会不会造成内存泄漏,但是Pagination在"loop: true"时,会出现计算错误,导致你所谓的bug。
修改如下:
$(function() {
$("button").click(function() {
var index = $(this).index();
var swiper;
$("body").find('.wrap-container').eq(index).show().siblings('.wrap-container').hide();
if(swiper !== undefined) {
swiper.destroy();
}
swiper = createSwiper(1 + index);
});
});
function createSwiper(index) {
var swiper = new Swiper('.swiper' + index, {
pagination: '.pagination' + index,
paginationClickable: true,
loop: true,
paginationBulletRender: function(index, className) {
return '<span class="' + className + '">' + (index + 1) + '</span>';
}
});
return swiper;
}
======================
目测真的是Swiper插件本身存在的Bug,对同一个swiper重复进行初始化后,Pagination就无法使用了,楼主有空可以在官网那里反馈一下。
暂时想到一个解决方案是用两个全局变量来保存两个Swiper的初始化状态,然后根据对应的index和swiper状态来判断是否进行初始化,如果您有更好的解决方案,麻烦也告知一下,谢谢!
$(function(){
var swiper1, swiper2;
$("button").click(function(){
var index = $(this).index();
$("body").find('.wrap-container').eq(index).show().siblings('.wrap-container').hide();
if(index === 0 && swiper1 === undefined) {
swiper1 = createSwiper(1);
} else if(index === 1 && swiper2 === undefined) {
swiper2 = createSwiper(2);
}
});
});
function createSwiper(index){
var swiper = new Swiper('.swiper'+index, {
pagination: '.pagination'+index,
paginationClickable: true,
loop:true,
paginationBulletRender: function (index, className) {
return '<span class="' + className + '">'+(index+1)+'</span>';
}
});
return swiper;
}
这篇关于javascript - 切换多个swiper之后滑动轮播图底下的分页器不动了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文